将文本文件逐行读入字符串

Read a text file line by line into strings

如何在不使用 BufferedReader 的情况下将文本文件的内容逐行读入 String

例如,我有一个文本文件,里面看起来像这样:

Purlplemonkeys
greenGorilla

我想创建两个 strings,然后使用类似这样的东西

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"

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

你应该使用 ArrayList.

File file = new File(fileName);
Scanner input = new Scanner(file);
List<String> list = new ArrayList<String>();

while (input.hasNextLine()) {
    list.add(input.nextLine());
}

然后您可以从其索引访问列表的一个特定元素,如下所示:

System.out.println(list.get(0));

这将为您提供第一行(即:Purlplemonkeys)

如何使用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
});

Sinse JDK 7 很容易将文件读入行:

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

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

您可以读取文本文件列出:

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

然后根据需要访问每一行

P.S。文件 - java.nio.file.Files

如果您使用 Java 7 或更高版本

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

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

您可以使用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();
 }

也可以通过覆盖 boolean isValidLine(String line) 方法来验证行。 refer doc