简体   繁体   English

从文本文件读入数组-获取“空”

[英]Reading from a text file into an array - getting “nulls”

I'm reading from a file and copying that into an array. 我正在从文件读取并将其复制到数组中。 My file has five lines of text, a sentence each. 我的文件有五行文字,每行一个句子。 I get my output "Array size is 5" but nothing after that. 我得到我的输出“数组大小为5”,但此后什么也没有。 If I do add a print line of the array, it gives me 5 nulls... 如果我确实添加了数组的打印行,它会给我5个空值...

Can someone help explain what I did wrong? 有人可以帮忙解释我做错了什么吗? Thanks! 谢谢!

 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; } } 

In this code 在这段代码中

    int count = 0;
    if (input.hasNextLine())   

The above hasNextLine will always be false as you have already read all the way through the file. 上面的hasNextLine始终为false,因为您已经阅读了整个文件。

Either reset the scanner to the beginning of the file, or use a dynamic list eg ArrayList to add the elements to. 将扫描仪重置为文件的开头,或者使用动态列表(例如ArrayList将元素添加到其中。

My Java is a bit rusty, but the basic gist of my answer is that you should create a new Scanner object so that it reads from the beginning of the file again. 我的Java有点生锈,但是我回答的基本要点是,您应该创建一个新的Scanner对象,以便它再次从文件的开头读取。 This is the easiest way to "reset" to the beginning. 这是“重置”开始的最简单方法。

Your code is currently not working because when you call input.nextLine() you're actually incrementing the scanner, and thus at the end of that first while() loop input is sitting at the end of the file, so when you call input.nextLine() again it returns null . 您的代码当前无法正常工作,因为当您调用input.nextLine()您实际上是在增加扫描程序,因此,在第一个while()循环的末尾,循环input位于文件的末尾,因此当您调用input.nextLine()再次返回null

Scanner newScanner = new Scanner(textFile);  

Then in the bottom of your code, your loop should look like this instead: 然后在代码底部,循环应改为:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM