Hola He creado dos enfoques para crear archivos de gran tamaño, los programas de gestión en Windows 7, 64 bits, 8 GB de RAM, JDK 8 y siguientes son resultados.
En ambos casos, se creó un archivo de 180 MB que contiene un número en cada línea de 1 a 20 millones (2 millones de rupias en el sistema de la India).
memoria de programa de Java crece gradualmente hasta 600 MB
primera salida
Approach = approach-1 (Using FileWriter)
Completed file writing in milli seconds = 4521 milli seconds.
Salida segundo
Approach = approach-2 (Using FileChannel and ByteBuffer)
Completed file writing in milli seconds = 3590 milli seconds.
Una observación - Estoy posición (variable POS) calcular en el enfoque # 2, si lo comento, solo la última cuerda será visible debido a que se sobreescribirá en la posición, pero el tiempo se reducirá a casi 2000 milisegundos.
Código adjunto.
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;
public class TestLargeFile {
public static void main(String[] args) {
writeBigFile();
}
private static void writeBigFile() {
System.out.println("--------writeBigFile-----------");
long nanoTime = System.nanoTime();
String fn = "big-file.txt";
boolean approach1 = false;
System.out.println("Approach = " + (approach1 ? "approach-1" : "approach-2"));
int numLines = 20_000_000;
try {
if (approach1) {
//Approach 1 -- for 2 crore lines takes 4.5 seconds with 180 mb file size
approach1(fn, numLines);
} else {
//Approach 2 -- for 2 crore lines takes nearly 2 to 2.5 seconds with 180 mb file size
approach2(fn, numLines);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Completed file writing in milli seconds = " + TimeUnit.MILLISECONDS.convert((System.nanoTime() - nanoTime), TimeUnit.NANOSECONDS));
}
private static void approach2(String fn, int numLines) throws IOException {
StringBuilder sb = new StringBuilder();
FileChannel rwChannel = new RandomAccessFile(fn, "rw").getChannel();
ByteBuffer wrBuf;
int pos = 0;
for (int i = 1; i <= numLines; i++) {
sb.append(i).append(System.lineSeparator());
if (i % 100000 == 0) {
wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, pos, sb.length());
pos += sb.length();
wrBuf.put(sb.toString().getBytes());
sb = new StringBuilder();
}
}
if (sb.length() > 0) {
wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, pos, sb.length());
wrBuf.put(sb.toString().getBytes());
}
rwChannel.close();
}
private static void approach1(String fn, int numLines) throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= numLines; i++) {
sb.append(i).append(System.lineSeparator());
}
FileWriter fileWriter = new FileWriter(fn);
fileWriter.write(sb.toString());
fileWriter.flush();
fileWriter.close();
}
}
No es necesario borrar el archivo. Lo estás sobreescribiendo. –
¿Cuánto tiempo es el tiempo de CPU y cuánto tiempo de E/S ("sistema")? Para archivos grandes, la enorme cadena 'textToSave' puede dominar el tiempo. – Raedwald
No relacionado directamente con su pregunta: Puede considerar reestructurar la sentencia out.close() para que se pueda hacer en un bloque finally. En caso de que se genere un error al escribir, aún se cerraría. –