简体   繁体   中英

Store entire line of text file in array line by line (not word by word; include spaces)

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.

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.

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()

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