¿Cómo puede Java leer un archivo de texto enorme sin desbordar la memoria y garantizar el rendimiento?
importar java.io.BufferedReader;
importar java.io.File;
importar java.io.FileReader;
importar java.io.RandomAccessFile;
importar java.nio.ByteBuffer;
importar java.nio.MappedByteBuffer;
importar java.nio.channels.FileChannel;
public class ReadBig {
public static String fff = "C:\\mq\\read\\from.xml";
public static void main1 (String[] args) lanza una excepción {
final int BUFFER_SIZE = 0x300000;//El tamaño del búfer es 3M
File f = new File(fff);
/**
*
* map(modo FileChannel.MapMode, posición larga, tamaño largo)
*
* modo: uno de * READ_ONLY, READ_WRITE o PRIVATE, respectivamente, según se define en la clase FileChannel.MapMode
dependiendo de si el archivo está asignado como de solo lectura, lectura/escritura o privado (copia en -write)
*
* posición: la posición en el archivo desde donde comienza el área de mapeo no debe ser negativa
*
;* tamaño: el tamaño del área a mapear no debe ser negativo ni mayor que Integer.MAX_VALUE
*
* Entonces, si desea leer el segunda mitad del archivo, como está escrito en el ejemplo. Si desea leer el último 1/8 del texto, debe escribir map(FileChannel.MapMode.READ_ONLY,
* f.length; ()*7/8,f.length()/8)
*
* Si desea leer todo el contenido del archivo, debe escribir map(FileChannel .MapMode.READ_ONLY, 0,f.length())
*
*/
MappedByteBuffer inputBuffer = new RandomAccessFile(f, "r")
.getChannel().map(FileChannel.MapMode.READ_ONLY,
f.length() / 2, f.length() / 2);
byte[] dst = new byte[BUFFER_SIZE];//Leer contenido de 3M cada vez
long start = System.currentTimeMillis();
for (int offset = 0; offset < inputBuffer.capacidad(); compensación += BUFFER_SI
ZE) {
if (inputBuffer.capacity() - offset >= BUFFER_SIZE) {
for (int i = 0; i < BUFFER_SIZE; i++)
dst[i] = inputBuffer.get(offset + i);
} else {
for (int i = 0; i < inputBuffer.capacity() - offset; i++ )
dst[i] = inputBuffer.get(offset + i);
}
int longitud = (inputBuffer.capacity() % BUFFER_SIZE == 0) ? BUFFER_SIZE
: inputBuffer.capacity() % BUFFER_SIZE;
System.out.println(new String(dst, 0, length));// nuevo
// String(dst,0,length) puede extraer la cadena guardada en el caché y operar con ella
}
long end = System.currentTimeMillis() ;
System.out.println("Leer la mitad del archivo tarda: " + (final - inicio) + "milisegundos");
}
public static void main2(String[] args) lanza una excepción {
int bufSize = 1024;
byte[] bs = new byte[bufSize];
ByteBuffer byteBuf = ByteBuffer.allocate(1024);
canal FileChannel = new RandomAccessFile(fff, "r").getChannel();
while (channel.read(byteBuf) ! = -1) {
int size = byteBuf.position();
byteBuf.rewind();
byteBuf.get(bs); // Trate el archivo como una cadena e imprímalo directamente como ejemplo.
System.out.print(new String(bs, 0, size));
byteBuf.clear();
}
}
public static void main(String[] args) lanza una excepción {
BufferedReader br = new BufferedReader(new FileReader(fff));
Línea de cadena = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}