简体   繁体   中英

Reading arraylist from a .txt file

I have an app where user inputs certain words and those words are saved to a .txt file on the device. Then I'm creating arraylist from that .txt file. This is the code:

try {
        Scanner s = new Scanner(recordedFiles);
        recordedFilesArray = new ArrayList<String>();
        while (s.hasNext()){
            recordedFilesArray.add(s.next());
        }
        s.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Now, the problem is that this puts each word to arraylist, not each line. So if user inputs (for example) 'test1', it'll add it to arraylist as test1 (which is fine), but if user inputs 'test 1' (with a space), 'test' and '1' will be added to arraylist as seperate elements.

Showing an example how it should work:

How text file looks like (example)

test 1

test 2

test 3

How arraylist looks like now:

test

1

test

2

test

3

How arraylist should look like:

test 1

test 2

test 3

So my question is; how do I add LINES to arraylist, not seperate words from a .txt file

Use .nextLine() which functions as follows:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

As Matt Ball has indicated the while loop should use hasNextLine() instead of hasNext()

    try {
        Scanner s = new Scanner(recordedFiles);
        recordedFilesArray = new ArrayList<String>();
        while (s.hasNextLine()){
            recordedFilesArray.add(s.nextLine());
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        s.close(); //close file on success or error
    }

Documentation

Instead of using scanner.next(); use scanner.nextLine();

您可以使用scanner.nextLine();

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