Java: How to read a text file

后端 未结 9 2304
青春惊慌失措
青春惊慌失措 2020-11-22 06:58

I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of t

9条回答
  •  生来不讨喜
    2020-11-22 07:20

    Java 1.5 introduced the Scanner class for handling input from file and streams.

    It is used for getting integers from a file and would look something like this:

    List integers = new ArrayList();
    Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
    while (fileScanner.hasNextInt()){
       integers.add(fileScanner.nextInt());
    }
    

    Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.

提交回复
热议问题