Search code examples
javaarraysstringline

Read a text file line by line into strings


How do I read the contents of a text file line by line into String without using a BufferedReader?

For example, I have a text file that looks like this inside:

Purlplemonkeys
greenGorilla

I would want to create two strings, then use something like this

File file = new File(System.getProperty("user.dir") + "\Textfile.txt");
String str = new String(file.nextLine());
String str2 = new String(file.nextLine());

That way it assigns str the value of "Purlplemonkeys", and str2 the value of "greenGorilla".


Solution

  • You should use an ArrayList.

    File file = new File(fileName);
    Scanner input = new Scanner(file);
    List<String> list = new ArrayList<String>();
    
    while (input.hasNextLine()) {
        list.add(input.nextLine());
    }
    

    Then you can access to one specific element of your list from its index as next:

    System.out.println(list.get(0));
    

    which will give you the first line (ie: Purlplemonkeys)