简体   繁体   English

逐行将文本文件读取为字符串

[英]Read a text file line by line into strings

How do I read the contents of a text file line by line into String without using a BufferedReader ? 如何在不使用BufferedReader情况下将文本文件的内容逐行读取为String

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 我想创建两个strings ,然后使用类似的东西

File file = new File(System.getProperty("user.dir") + "\Textfile.txt");
String str = new String(file.nextLine());
String str2 = new String(file.nextLine());

That way it assigns str the value of "Purlplemonkeys" , and str2 the value of "greenGorilla" . 这样,它分配str的价值"Purlplemonkeys" ,和str2的价值"greenGorilla"

You can read text file to list: 您可以阅读文本文件以列出:

List<String> lst = Files.readAllLines(Paths.get("C:\\test.txt"));

and then access each line as you want 然后根据需要访问每一行

PS Files - java.nio.file.Files PS文件-java.nio.file.Files

You should use an ArrayList . 您应该使用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));

which will give you the first line (ie: Purlplemonkeys) 这将给您第一行(即:Purlplemonkeys)

If you use Java 7 or later 如果您使用Java 7或更高版本

List<String> lines = Files.readAllLines(new File(fileName));

for(String line : lines){
   // Do whatever you want
   System.out.println(line);
}

Sinse JDK 7 is quite easy to read a file into lines: Sinse JDK 7非常容易将文件读取为几行:

List<String> lines = Files.readAllLines(new File("text.txt").toPath())

String p1 = lines.get(0);
String p2 = lines.get(1);

How about using commons-io : 如何使用commons-io

List<String> lines = org.apache.commons.io.IOUtils.readLines(new FileReader(file));

//Direct access if enough lines read
if(lines.size() > 2) {
  String line1 = lines.get(0);
  String line2 = lines.get(1);
}

//Iterate over all lines
for(String line : lines) {
  //Do something with lines
}

//Using Lambdas
list.forEach(line -> {
  //Do something with line
});

You can use apache.commons.io.LineIterator 您可以使用apache.commons.io.LineIterator

LineIterator it = FileUtils.lineIterator(file, "UTF-8");
 try {
   while (it.hasNext()) {
     String line = it.nextLine();
     // do something with line
   }
 } finally {
   it.close();
 }

One can also validate line by overriding boolean isValidLine(String line) method. 也可以通过重写boolean isValidLine(String line)方法来验证行。 refer doc 参考文件

File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
  System.out.println(input.nextLine());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM