java – 使用DataInputStream从文件读取非常慢
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 使用DataInputStream从文件读取非常慢,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1803字,纯文字阅读大概需要3分钟。
内容图文
我有一个包含大量数字的文件.
我曾尝试使用以下代码从文件中读取它,但它是超级慢任何人都可以帮助减少时间?
以下是我的代码以非常慢的方式阅读它:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class FileInput {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
String filename = scan1.nextLine();
File file = new File(filename);
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
解决方法:
不要使用DataInputStream从文件中读取行.而是使用BufferedReader,如:
fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
while ((String line = reader.readLine()) != null) {
System.out.println(line);
}
DataInputStream.readLine上的javadoc告诉您不要使用该方法. (它已被弃用)
当然,当你真正开始阅读这些数字时,我会鼓励你忘记自己阅读这些行,然后让Scanner为你读取这些数字.如果您需要知道哪些数字在同一行,Scanner也可以为您做到这一点:
Scanner fileScanner = new Scanner(file, "UTF-8").useDelimiter(" +| *(?=\\n)|(?<=\\n) *");
while (fileScanner.hasNext()) {
List<Integer> numbersOnLine = new ArrayList<Integer>();
while (fileScanner.hasNextInt()) {
numbersOnLine.add(fileScanner.nextInt());
}
processLineOfNumbers(numbersOnLine);
if (fileScanner.hasNext()) {
fileScanner.next(); // clear the newline
}
}
这个花哨的正则表达式使得行之间的换行符也显示为扫描器的标记.
内容总结
以上是互联网集市为您收集整理的java – 使用DataInputStream从文件读取非常慢全部内容,希望文章能够帮你解决java – 使用DataInputStream从文件读取非常慢所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。