Guy
Guy

Reputation: 6522

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

Upvotes: 1

Views: 915

Answers (4)

ThePerson
ThePerson

Reputation: 3236

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

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

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

Upvotes: 5

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

You can use scanner.nextLine();

Upvotes: 0

Related Questions