Java: How to read a text file

后端 未结 9 2251
青春惊慌失措
青春惊慌失措 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:10

    Use Apache Commons (IO and Lang) for simple/common things like this.

    Imports:

    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang3.ArrayUtils;
    

    Code:

    String contents = FileUtils.readFileToString(new File("path/to/your/file.txt"));
    String[] array = ArrayUtils.toArray(contents.split(" "));
    

    Done.

提交回复
热议问题