[英]Reading from a text file into an array - getting “nulls”
我正在从文件读取并将其复制到数组中。 我的文件有五行文字,每行一个句子。 我得到我的输出“数组大小为5”,但此后什么也没有。 如果我确实添加了数组的打印行,它会给我5个空值...
有人可以帮忙解释我做错了什么吗? 谢谢!
public static int buildArray() throws Exception { System.out.println("BuildArray is starting "); java.io.File textFile; // declares a variable of type File textFile = new java.io.File ("textFile.txt"); //reserves the memory Scanner input = null; try { input = new Scanner(textFile); } catch (Exception ex) { System.out.println("Exception in method"); System.exit(0); } int arraySize = 0; while(input.hasNextLine()) { arraySize = arraySize + 1; if (input.nextLine() == null) break; } System.out.println("Array size is " + arraySize); // Move the lines into the array String[] linesInRAM = new String[arraySize];// reserve the memory int count = 0; if (input.hasNextLine()) { while(count < arraySize) { System.out.println("test"); linesInRAM[count] = input.nextLine(); System.out.println(linesInRAM[count]); count = count + 1; } }
在这段代码中
int count = 0;
if (input.hasNextLine())
上面的hasNextLine
始终为false,因为您已经阅读了整个文件。
将扫描仪重置为文件的开头,或者使用动态列表(例如ArrayList
将元素添加到其中。
我的Java有点生锈,但是我回答的基本要点是,您应该创建一个新的Scanner对象,以便它再次从文件的开头读取。 这是“重置”开始的最简单方法。
您的代码当前无法正常工作,因为当您调用input.nextLine()
您实际上是在增加扫描程序,因此,在第一个while()
循环的末尾,循环input
位于文件的末尾,因此当您调用input.nextLine()
再次返回null
。
Scanner newScanner = new Scanner(textFile);
然后在代码底部,循环应改为:
if (newScanner.hasNextLine())
{
while(count < arraySize)
{
System.out.println("test");
linesInRAM[count] = newScanner.nextLine();
System.out.println(linesInRAM[count]);
count = count + 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.