[英]How to make Java read very big files using Scanner?
我正在使用以下基本功能,我从网上复制读取文本文件
public void read ()
{
File file = new File("/Users/MAK/Desktop/data.txt");
System.out.println("Start");
try
{
//
// Create a new Scanner object which will read the data from the
// file passed in. To check if there are more line to read from it
// we check by calling the scanner.hasNextLine() method. We then
// read line one by one till all line is read.
//
Scanner scanner = new Scanner(file);
int lineCount = 0;
if (scanner == null)
{
System.out.println("Null File");
}
else
{
System.out.println(scanner.toString());
}
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println("Line " + lineCount +" contain : " + line);
lineCount++;
}
System.out.println("End of Try Bluck");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
System.out.println("Exception Bluck");
}
System.out.println("End");
}
}
它适用于中小型文件(包含10到2万行数据)但是它无法使用包含50万行的文件。 我没有收到错误(至少没有看到任何人)。 那么发生了什么? 我该怎么做才能准备好这么大的文件?
注意:我已经在运行Windows Server 2008且4 GB内存的测试计算机上增加了2 GB的堆。 但这没有多大帮助!
请有人能告诉我这里应该做些什么吗?
更新01
以下是输出
开始
java.util.Scanner [delimiters = \\ p {javaWhitespace} +] [position = 0] [match valid = false] [need input = false] [source closed = false] [skipped = false] [group separator = \\,] [decimal separator =。] [positive prefix =] [negative prefix = \\ Q- \\ E] [positive suffix =] [negative suffix =] [NaN string = \\Q \\ E] [infinity string = \\Q∞\\ E ]
尝试Bluck结束
结束
最好使用FileReader获取BufferedReader
如果你没有收到错误,那可能需要很长时间。 磁盘仍然有效吗? 你在做什么与控制台输出 - 它停止了吗? 你说它“无法工作”,但你还没有说它是如何表现的。 你在看什么?
内存应该不是问题,因为你实际上没有对这些行做任何事情 - 只计算它们并将它们写入控制台。
代码中的一个问题 - 您正在检查scanner
是否为空,但它不可能 ,因为您正在使用构造函数调用返回的引用。 你想要应对什么情况?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.