0

I am writing a program where the contents of a text file will be stored in an array line by line. I have it working, but it's only storing one word at a time.

  try ( Scanner fin = new Scanner ( new File("toDoItems.txt") ); ) 
    {
    for (int i = 0; i < listCount && fin.hasNext(); i++) 
          {
          textItem[i] = fin.next();
          }
    }

The listCount variable stores how many lines to read from the file, from the top. Instead it is telling it how many words to read. What can I do to read the entire line into the Array, without knowing how long each line may be?

I set the array size to much larger than I need and I am using the following to display the items one line at a time and only displaying the items in use (so to avoid a long list of nulls)

    for (int i = 0; i < listCount; i++) 
          {
              String temp = textItem[i];
              System.out.println(temp);
          }

(For this I am restricted to arrays only. No Arraylists or lists)

Note: Most similar questions I could find are only attempting to store lines that contain a single word.

Elliander
  • 503
  • 1
  • 9
  • 19

2 Answers2

1

Change fin.hasNext() to fin.hasNextLine() and fin.next() to fin.nextLine().

For future reference, you can find that kind of information in the official documentation.

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
1

In Java8, you can use stream with limit to yield file list content line by line:

 List<String> contents = Files.lines(Paths.get("toDoItems.txt")).limit(listCount).collect(Collectors.toList());

fin.next() will get the next input by token. it should be fin.nextLine()

chengpohi
  • 14,064
  • 1
  • 24
  • 42