java大文件如何写入,用java读取和写入大文件

My idea is to make a little software that reads a file (which can't be read "naturally", but it contains some images), turns its data into hex, looks for the PNG chunks (a kind of marks that are at the beginning and end of a .png file), and saves the resulting data in different files (after getting it back from hex). I am doing this in Java, using a code like this:

// out is where to show the result and file is the source

public static void hexDump(PrintStream out, File file) throws IOException {

InputStream is = new FileInputStream(file);

StringBuffer Buffer = new StringBuffer();

while (is.available() > 0) {

StringBuilder sb1 = new StringBuilder();

for (int j = 0; j < 16; j++) {

if (is.available() > 0) {

int value = (int) is.read();

// transform the current data into hex

sb1.append(String.format("%02X ", value));

}

}

Buffer.append(sb1);

// Should I look for the PNG here? I'm not sure

}

is.close();

// Print the result in out (that may be the console or a file)

out.print(Buffer);

}

I'm sure there are another ways to do this using less "machine-resources" while opening huge files. If you have any idea, please tell me. Thanks!

This is the first time I post, so if there is any error, please help me to correct it.

解决方案

Reading the file a byte at a time would be taking substantial time here. You can improve that by orders of magnitude. You should be using a DataInputStream around a BufferedInputStream around the FileInputStream, and reading 16 bytes at a time with readFully.

And then processing them, without conversion to and from hex, which is quite unnecessary here, and writing them to the output(s) as you go, via a BufferedOutputStream around the FileOutputStream, rather than concatenating the entire file into memory and having to write it all out in one go. Of course that takes time, but that's because it does, not because you have to do it that way.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值