java 读文件 二进制文件,用Java读取二进制文件

一篇关于Java程序员在处理大量未签名64位整数文件时遇到的读取瓶颈,探讨了使用`long`类型的原因,以及如何通过使用BufferedInputStream改进DataInputStream的示例。作者寻求提高文件读取速度,以匹配C++同行的4秒读取时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a comparatively long file of unsigned integers (64 bits each, 0.47GB file) that I need to read and store in an array. After some brain racking I wound up using the type long, since everything in Java is signed (correct me if I'm wrong, please) and I couldn't think of a better alternative. Anyhow, the array only has to be sorted, so the precise values of the original numbers are not of the utmost importance. We're supposed to measure the efficiency of the sorting algorithm, nothing more. However, I came up against a brick wall when I actually came to reading the file (my code below).

public class ReadFileTest {

public static void main(String[] args) throws Exception {

String address = "some/directory";

File input_file = new File (address);

FileInputStream file_in = new FileInputStream(input_file);

DataInputStream data_in = new DataInputStream (file_in );

long [] array_of_ints = new long [1000000];

int index = 0;

long start = System.currentTimeMillis();

while(true) {

try {

long a = data_in.readLong();

index++;

System.out.println(a);

}

catch(EOFException eof) {

System.out.println ("End of File");

break;

}

}

System.out.println(index);

System.out.println(System.currentTimeMillis() - start);

}

}

It goes on and on forever, and I usually step out to have lunch while the programme's reading. All in all 20 minutes is the fastest I've achieved so far. A course mate bragged today that his programme read it in 4 sec. He's working in C++ and I know that C++ is faster than Java, but this is ridiculous. Could somebody, please, tell me what I'm doing wrong here. I can't blame it on the language or the machine, so it must be me. From what I can see, though, the Java tutorials use exactly the same class, i.e. DataInputStream. I also saw FileChannels being recommended a couple of times. Are they the only way out?

解决方案

You should use buffered input, something like:

new DataInputStream(

new BufferedInputStream(

new FileInputStream(new File(input_file))))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值