Java: How to read a text file

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

    Just for fun, here's what I'd probably do in a real project, where I'm already using all my favourite libraries (in this case Guava, formerly known as Google Collections).

    String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
    List list = Lists.newArrayList();
    for (String s : text.split("\\s")) {
        list.add(Integer.valueOf(s));
    }
    

    Benefit: Not much own code to maintain (contrast with e.g. this). Edit: Although it is worth noting that in this case tschaible's Scanner solution doesn't have any more code!

    Drawback: you obviously may not want to add new library dependencies just for this. (Then again, you'd be silly not to make use of Guava in your projects. ;-)

提交回复
热议问题