Java:如何读取文本文件
我想读取包含空格分隔值的文本文件。值是整数。 如何读取它并将其放入数组列表中?
以下是文本文件内容的示例:
1 62 4 55 5 6 77
我希望将其作为 [1, 62, 4, 55, 5, 6, 77]
放入数组列表中。我怎样才能用Java做到这一点?
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 the text file:
1 62 4 55 5 6 77
I want to have it in an arraylist as [1, 62, 4, 55, 5, 6, 77]
. How can I do it in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
到目前为止给出的所有答案都涉及逐行读取文件,将该行作为
String
,然后处理String
。毫无疑问,这是最容易理解的方法,如果文件相当短(比如几万行),从效率角度来说也是可以接受的。 但是如果文件很长,这是一种非常低效的方法,原因有两个:
String
时,一次是在处理中它。String
,然后在移动到下一行时将其丢弃。垃圾收集器最终将不得不处理所有这些您不再需要的String
对象。必须有人在你身后清理。如果您关心速度,那么读取数据块然后逐字节处理它比逐行处理要好得多。每次到达数字末尾时,都会将其添加到正在构建的
List
中。它会出现这样的结果:
上面的代码假设这是 ASCII(尽管它可以很容易地调整为其他编码),并且任何不是数字的东西(特别是空格或换行符)都代表边界数字之间。它还假设文件以非数字结尾(实际上,最后一行以换行符结尾),不过,可以再次对其进行调整以处理不是数字的情况。
它比任何基于
String
的方法(也作为该问题的答案给出)快得多。 在此问题中。您会看到,如果您想继续使用多线程,则可以进一步改进它。All the answers so far given involve reading the file line by line, taking the line in as a
String
, and then processing theString
.There is no question that this is the easiest approach to understand, and if the file is fairly short (say, tens of thousands of lines), it'll also be acceptable in terms of efficiency. But if the file is long, it's a very inefficient way to do it, for two reasons:
String
, and once in processing it.String
for each line, and then throwing it away when you move to the next line. The garbage collector will eventually have to dispose of all theseString
objects that you don't want any more. Someone's got to clean up after you.If you care about speed, you are much better off reading a block of data and then processing it byte by byte rather than line by line. Every time you come to the end of a number, you add it to the
List
you're building.It will come out something like this:
The code above assumes that this is ASCII (though it could be easily tweaked for other encodings), and that anything that isn't a digit (in particular, a space or a newline) represents a boundary between digits. It also assumes that the file ends with a non-digit (in practice, that the last line ends with a newline), though, again, it could be tweaked to deal with the case where it doesn't.
It's much, much faster than any of the
String
-based approaches also given as answers to this question. There is a detailed investigation of a very similar issue in this question. You'll see there that there's the possibility of improving it still further if you want to go down the multi-threaded line.读取文件,然后做你想做的事
java8
Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());
read the file and then do whatever you want
java8
Files.lines(Paths.get("c://lines.txt")).collect(Collectors.toList());
您可以使用
Files#readAllLines()
将文本文件的所有行获取到List
中。教程: 基本 I/O >文件I/O>读取、写入和创建文本文件
您可以使用
String#split()
根据正则表达式将String
分成几部分。教程: 数字和字符串 >字符串>操作字符串中的字符
您可以使用
Integer#valueOf()
将String
转换为Integer
。教程: 数字和字符串 >字符串>数字和字符串之间的转换
您可以使用
List#add()
将元素添加到List
。教程: 接口 >列表接口
所以,简而言之(假设文件没有空行,也没有尾随/前导空格)。
如果您碰巧已经使用 Java 8,那么您甚至可以使用 Stream API 为此,从
Files#lines()
。教程:使用 Java 8 流处理数据
You can use
Files#readAllLines()
to get all lines of a text file into aList<String>
.Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
You can use
String#split()
to split aString
in parts based on a regular expression.Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use
Integer#valueOf()
to convert aString
into anInteger
.Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings
You can use
List#add()
to add an element to aList
.Tutorial: Interfaces > The List Interface
So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).
If you happen to be at Java 8 already, then you can even use Stream API for this, starting with
Files#lines()
.Tutorial: Processing data with Java 8 streams
Java 1.5 引入了 Scanner 类用于处理来自文件和流的输入。
它用于从文件中获取整数,看起来像这样:
不过请检查 API。还有更多选项可用于处理不同类型的输入源、不同的分隔符和不同的数据类型。
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:
Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.
此示例代码向您展示了如何用 Java 读取文件。
This example code shows you how to read file in Java.
看一下这个例子,并尝试做你自己的:
Look at this example, and try to do your own:
只是为了好玩,这就是我在实际项目中可能会做的事情,其中我已经使用了所有我最喜欢的库(在本例中 Guava,以前称为Google Collections)。
好处:不需要维护太多自己的代码(与例如 这个)。 编辑:尽管值得注意的是,在这种情况下 tschaible 的扫描仪解决方案 没有更多代码!
缺点:您显然可能不想为此添加新的库依赖项。 (话又说回来,如果你不在你的项目中使用 Guava,那你就太傻了。;-)
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).
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. ;-)
使用 Apache Commons(IO 和 Lang)来处理类似这样的简单/常见的事情。
导入:
代码:
完成。
Use Apache Commons (IO and Lang) for simple/common things like this.
Imports:
Code:
Done.
使用 Java 7 通过 NIO.2 读取文件
导入这些包:
这是读取文件的过程:
一次读取文件的所有行:
Using Java 7 to read files with NIO.2
Import these packages:
This is the process to read a file:
To read all lines of a file at once: