import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
public class GeradorNumerosAleatoriosEmArquivo {
public static final String NOME_ARQUIVO = "numeros.txt";
private static void escreverArquivo(int[] v) throws IOException {
File f = new File(NOME_ARQUIVO);
if (f.exists()) {
f.delete();
}
FileOutputStream fos = new FileOutputStream(NOME_ARQUIVO);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(v.length);
for (int element : v) {
dos.writeInt(element);
}
fos.close();
long length = new File(NOME_ARQUIVO).length();
System.out.println("Arquivo gerado: " + length + " bytes");
}
public static int[] lerArquivo(String nomeArquivo) throws IOException {
FileInputStream fis = new FileInputStream(nomeArquivo);
DataInputStream dis = new DataInputStream(fis);
int size = dis.readInt();
int[] v = new int[size];
for (int i = 0; i < size; i++) {
v[i] = dis.readInt();
}
fis.close();
System.out.println("Arquivo lido: " + size + " números");
return v;
}
private static int[] gerarVetor(int tamanho, int limite) {
int[] v = new int[tamanho];
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < tamanho; i++) {
v[i] = Math.abs((r.nextInt() % limite)) + 1;
}
return v;
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int tamanho = 100000;
int limite = 200000;
int[] v = gerarVetor(tamanho, limite);
System.out.println(v.length);
escreverArquivo(v);
v = lerArquivo(NOME_ARQUIVO);
System.out.println(v.length);
}
}