逐行读取文本文件到字符串中 [英] Read a text file line by line into strings
本文介绍了逐行读取文本文件到字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不使用 BufferedReader
的情况下逐行将文本文件的内容读入 String
?
How do I read the contents of a text file line by line into String
without using a BufferedReader
?
例如,我有一个看起来像这样的文本文件:
For example, I have a text file that looks like this inside:
Purlplemonkeys
greenGorilla
我想创建两个字符串
,然后使用类似这样的东西
I would want to create two strings
, then use something like this
File file = new File(System.getProperty("user.dir") + "\Textfile.txt");
String str = new String(file.nextLine());
String str2 = new String(file.nextLine());
这样它就分配 str
的值Purlplemonkeys
, str2
greenGorilla的价值
。
That way it assigns str
the value of "Purlplemonkeys"
, and str2
the value of "greenGorilla"
.
推荐答案
你应该使用 ArrayList
。
File file = new File(fileName);
Scanner input = new Scanner(file);
List<String> list = new ArrayList<String>();
while (input.hasNextLine()) {
list.add(input.nextLine());
}
然后你可以从索引中访问列表中的一个特定元素作为下一个:
Then you can access to one specific element of your list from its index as next:
System.out.println(list.get(0));
这将为您提供第一行(即:Purlplemonkeys)
which will give you the first line (ie: Purlplemonkeys)
这篇关于逐行读取文本文件到字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文