如何从大文件中有效读取数据并使用Java NIO
框架将批量数据写入文件中。使用Java读取和写入大文件NIO
我与ByteBuffer
和FileChannel
工作,并曾尝试类似如下:
public static void main(String[] args)
{
String inFileStr = "screen.png";
String outFileStr = "screen-out.png";
long startTime, elapsedTime;
int bufferSizeKB = 4;
int bufferSize = bufferSizeKB * 1024;
// Check file length
File fileIn = new File(inFileStr);
System.out.println("File size is " + fileIn.length() + " bytes");
System.out.println("Buffer size is " + bufferSizeKB + " KB");
System.out.println("Using FileChannel with an indirect ByteBuffer of " + bufferSizeKB + " KB");
try ( FileChannel in = new FileInputStream(inFileStr).getChannel();
FileChannel out = new FileOutputStream(outFileStr).getChannel())
{
// Allocate an indirect ByteBuffer
ByteBuffer bytebuf = ByteBuffer.allocate(bufferSize);
startTime = System.nanoTime();
int bytesCount = 0;
// Read data from file into ByteBuffer
while ((bytesCount = in.read(bytebuf)) > 0) {
// flip the buffer which set the limit to current position, and position to 0.
bytebuf.flip();
out.write(bytebuf); // Write data from ByteBuffer to file
bytebuf.clear(); // For the next read
}
elapsedTime = System.nanoTime() - startTime;
System.out.println("Elapsed Time is " + (elapsedTime/1000000.0) + " msec");
}
catch (IOException ex) {
ex.printStackTrace();
}
}
谁能告诉我应该遵循同样的程序,如果在超过2 GB我的文件的大小?
如果书写操作是批量书写时我想要做的类似的事情,我该怎么办?
的
FileInputStream
/FileOutputStream
绕道你们是不是来处理的数据,或者你只是想复制呢? – Kayaman'如果我想要做类似的事情'是什么意思? – EJP