简体   繁体   English

从FileReader读取多行

[英]Reading multiple lines from FileReader

*Edit as I cannot use anything other than Scanner class. *编辑,因为除Scanner类外,我无法使用其他任何东西。

I'm reading in a text file for a Conway's Game of Life program that looks like so: 我正在阅读Conway的“人生游戏”程序的文本文件,如下所示:

------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
-------------X-X-X------------
--------------XXX-------------
-------------X-X-X------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------

I am trying to read all the characters into a single string variable and then parsing the string into a char array. 我试图将所有字符读入单个字符串变量,然后将字符串解析为char数组。 How would I fix my code for the FileReader to read all the lines, and not stop after reaching the end of one? 我该如何修复我的代码,使FileReader读取所有行,并且在到达一行的结尾后不停止?

    inputfile = JOptionPane.showInputDialog ("Where is the input file?   Ex:                   C:\\users\\public\\desktop\\input.txt ");
    Scanner input = new Scanner (new FileReader(inputfile)); 
    String values = null;
    while(input.hasNextLine()){
    values = input.next();
    }
    System.out.println(values);

input is path of the file (the user entered to the popup). 输入是文件的路径(用户输入到弹出窗口)。 Not the content of the file. 不是文件的内容。

Here is a way to read a file line by line 这是一种逐行读取文件的方法

Java read line from file Java从文件中读取行

Please note that you are overwriting value in your loop every time (you do value = input.next(); ). 请注意,您每次都会在循环中覆盖 value (执行value = input.next(); )。 I think you meant to add all lines together. 我认为您打算将所有行加在一起。 After the loop is finished, the value String only contains the last line read, and as such that is the only line printed to System.out . 循环完成后,值String仅包含读取的最后一行,因此,这是唯一打印到System.out

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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