java读取文件特别慢,Java:InputStream太慢,无法读取大文件

本文探讨了Java在处理大文件时(如183MB)与C++ ifstream相比的显著慢速问题。作者提出使用Java Native Interface将C++文件处理部分引入Java,同时讨论了缓冲输入流的局限,并给出了一个183MB文件耗时250ms的实验结果。寻求提高文件读取速度和可能的优化策略。
摘要由CSDN通过智能技术生成

I have to read a 53 MB file character by character. When I do it in C++ using ifstream, it is completed in milliseconds but using Java InputStream it takes several minutes. Is it normal for Java to be this slow or am I missing something?

Also, I need to complete the program in Java (it uses servlets from which I have to call the functions which process these characters). I was thinking maybe writing the file processing part in C or C++ and then using Java Native Interface to interface these functions with my Java programs... How is this idea?

Can anyone give me any other tip... I seriously need to read the file faster. I tried using buffered input, but still it is not giving performance even close to C++.

Edited: My code spans several files and it is very dirty so I am giving the synopsis

import java.io.*;

public class tmp {

public static void main(String args[]) {

try{

InputStream file = new BufferedInputStream(new FileInputStream("1.2.fasta"));

char ch;

while(file.available()!=0) {

ch = (char)file.read();

/* Do processing */

}

System.out.println("DONE");

file.close();

}catch(Exception e){}

}

}

解决方案

I ran this code with a 183 MB file. It printed "Elapsed 250 ms".

final InputStream in = new BufferedInputStream(new FileInputStream("file.txt"));

final long start = System.currentTimeMillis();

int cnt = 0;

final byte[] buf = new byte[1000];

while (in.read(buf) != -1) cnt++;

in.close();

System.out.println("Elapsed " + (System.currentTimeMillis() - start) + " ms");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值