-4

I am trying to read the following from a textfile

12

650 64 1

16 1024 2

How do I put this in a list or give them variables?

Tried this

class Test{
Scanner lese = new Scanner(new File("regneklynge.txt"));`
ArrayList<String> list = new ArrayList<String>();`
  while (lese.hasNext()){`
    list.add(lese.next());`
  }
}
Sam
  • 922
  • 1
  • 10
  • 23
H.Pett
  • 41
  • 4
  • 3
    What have you tried so far? Reading from a file in java is covered basically everywhere. – f1sh Jan 29 '18 at 10:58
  • 1
    Duplicate of https://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java – Monkey Supersonic Jan 29 '18 at 10:58
  • 3
    Possible duplicate of [How to read a large text file line by line using Java?](https://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java) – Monkey Supersonic Jan 29 '18 at 10:58
  • Possible duplicate of [Reading a plain text file in Java](https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) – Bernhard Barker Jan 29 '18 at 11:00

1 Answers1

0

Check this article our for reading from a file.

Then, you can use Java's Scanner class to read individual items and put them into a list.

For example:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;

public class ReadFromFile {

    public static void main(String[] args) {

        File file = new File("file-name.txt");

        try {

            Scanner scanner = new Scanner(file);

            List<Integer> myIntList = new ArrayList<>(); 
            while (scanner.hasNext()) {
                int i = scanner.nextInt();
                myIntList.add(i);
            }
            scanner.close();
            // now you have an ArrayList with the numbers in it that you can use
        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
peachykeen
  • 3,315
  • 4
  • 22
  • 38