即我有一个 10 mb 的文件,我想删除 1M 到 2M 的字节,所以生成的文件是 9mb,文件中的数据从 2m 字节开始,现在从 1M 开始
我使用 Java 7,因此可以使用 NIO,文件通常大小为 10MB,并且经常通过网络访问,因此我正在寻找一个性能良好的优雅解决方案。
我知道 BteBuffer.allocateDirect() 和 File.getChannel() 但我正在努力解决是否有办法做我想做的事情,而不涉及必须从文件 channel 写入 8MB 到临时缓冲区只是为了将它写回到不同位置的文件中,或者如果使用 allocateDirect() 这实际上没问题
最佳答案
将结果写入一个临时文件,然后用您的临时文件(充当磁盘上的缓冲区)替换旧文件。
代码示例:
public static void main(String[] args) {
// -- prepare files
File inFile = new File("D:/file.dat");
File outFile;
try {
outFile = File.createTempFile("swap", "buffer");
} catch (IOException ex) {
throw new IOError(ex);
}
// -- process file
try (
InputStream inStream = new FileInputStream(inFile);
OutputStream outStream = new FileOutputStream(outFile)
) {
//drop some bytes (will be removed)
inStream.skip(4);
//modify some bytes (will be changed)
for (int i = 0; i < 4; i++) {
byte b = (byte) inStream.read();
outStream.write(b >> 4);
}
//copy bytes in chunks (will be kept)
final int CHUNK_SIZE = 1024;
byte[] chunkBuffer = new byte[CHUNK_SIZE];
while (true) {
int chunkSize = inStream.read(chunkBuffer, 0, CHUNK_SIZE);
if (chunkSize < 0) {
break;
}
outStream.write(chunkBuffer, 0, chunkSize);
}
} catch (FileNotFoundException ex) {
throw new RuntimeException("input file not found!", ex);
} catch (IOException ex) {
throw new RuntimeException("failed to trim data!", ex);
}
// -- release changes
//replace inFile with outFile
inFile.delete();
outFile.renameTo(inFile);
}
关于java - 在 Java 7 中删除二进制文件的一部分的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32786629/