简体   繁体   中英

Reading multiple lines from FileReader

*Edit as I cannot use anything other than Scanner class.

I'm reading in a text file for a Conway's Game of Life program that looks like so:

------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
-------------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. How would I fix my code for the FileReader to read all the lines, and not stop after reaching the end of one?

    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

Please note that you are overwriting value in your loop every time (you do 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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