How to convert string text from notepad into array line by line?

Question

I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,

I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats

and so on..

In this case, the array[1] will be string 'I love banana and chicken'. The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:

import java.util.*;
import java.io.*;
import java.util.Scanner;

class Test
{
    public static void main(String[] args)
        throws Exception
    {
        File file = new File("notepad.txt");     
        Scanner scanner = new Scanner(file);  
        String line;
        int i = 0;
        int j = 0;

        while (scanner.hasNextLine()) {
            i++;
        }

        String[] stringArray = new String[i];

        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            stringArray[j] = line;
            j++;
        }

        System.out.println(stringArray[2]);

        scanner.close();
    }
}

I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.


Show source
| java   | file   | arrays   | string   | java.util.scanner   2017-01-06 19:01 3 Answers

Answers to How to convert string text from notepad into array line by line? ( 3 )

  1. 2017-01-06 19:01

    The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:

    String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
    
  2. 2017-01-06 19:01

    You can simply do it by creating an ArrayList and then converting it to the String Array.

    Here is a sample code to get you started:

    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(new File("notepad.txt"));
        List<String> outputList = new ArrayList<>();
    
        String input = null;
        while (in.hasNextLine() && null != (input = in.nextLine())) {
            outputList.add(input);
        }
    
        String[] outputArray = new String[outputList.size()];
        outputArray = outputList.toArray(outputArray);
    
        in.close();
    }
    
  3. 2017-01-06 19:01

    Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -

    List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));
    

Leave a reply to - How to convert string text from notepad into array line by line?

◀ Go back