1

This is what I have been working so far for reading a text file,

   Scanner file = new Scanner(new File("sample.txt")).useDelimiter(".");
   ArrayList<String> arr = new ArrayList<>();
   while (file.hasNextLine()) {
      strList.add(file.nextLine());
   }
   file.close();
   for (int i = 0; i < arr.size(); i++) {
      System.out.println(arr.get(i));
   }

and my text file looks like this,

I love you. You
love me. He loves
her. She loves him.

I want a result of the code like,

I love you
You love me
He loves her
She loves him

But the result is same as the text file itself. Isn't that "useDelimiter(".")" suppose to separate the text file with period(".")?

I've also tried to use hasNext() and next() instead of hasNextLine() and nextLine(), but it prints out empty 30ish new lines.

Mr.B
  • 29
  • 5

1 Answers1

3

That's because useDelimiter accepts a pattern. The dot . is a special character used for regular expressions meaning 'any character'. Simply escape the period with a backslash and it will work:

Scanner file = new Scanner(new File("sample.txt")).useDelimiter("\\.");

EDIT

The problem is, you're using hasNextLine() and nextLine() which won't work properly with your new . delimiter. Here's a working example that gets you the results you want:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test {

    final static String path = Test.class.getResource("sample.txt").getPath();

    public static void main(String[] args) throws IOException {
        Scanner file = new Scanner(new File(path)).useDelimiter("\\.");
        List<String> phrases = new ArrayList<String>();
        while (file.hasNext()) {
            phrases.add(file.next().trim().replace("\r\n", " ")); // remove new lines
        }
        file.close();

        for (String phrase : phrases) {
            System.out.println(phrase);
        }
    }
}

by using hasNext() and next(), we can use our new . delimiter instead of the default new line delimiter. Since we're doing that however, we've still go the new lines scattered throughout your paragraph which is why we need to remove new lines which is the purpose of file.next().trim().replace("\r\n", " ") to clean up the trailing whitespace and remove new line breaks.

Input:

I love you. You
love me. He loves
her. She loves him.

Output:

I love you
You love me
He loves her
She loves him
Jake Miller
  • 2,034
  • 1
  • 17
  • 38