eclipse 中的文件 reader
File reader in eclipse
谁能告诉我为什么我的代码从不读取文件的第二行?如果我在文件中的第二行(例如 .txt 文件)从一个新行开始并缩进该行,它将不会读取 it.But 如果它在一个新行中并且没有缩进,它将读取.它也可以读取第 3 行。它与 while 循环有关吗?
Scanner keyboard = new Scanner (System.in);
System.out.println("Input the file name");
String fileName = keyboard.nextLine();
File input = new File (fileName);
BufferedReader reader = new BufferedReader(new FileReader(input));
String content = reader.readLine();
content.replaceAll("\s+","");
while (reader.readLine() != null) {
content = content + reader.readLine();
}
System.out.println(content);
在下面的代码中查看我的评论。
String content = reader.readLine(); //here you read a line
content.replaceAll("\s+","");
while (reader.readLine() != null) //here you read a line (once per loop iteration)
{
content = content + reader.readLine(); //here you read a line (once per loop iteration)
}
如您所见,您正在读取 while 循环开头的第二行,并在继续之前检查它是否等于 null。但是,您对该值不做任何操作,它就丢失了。更好的解决方案如下所示:
String content = ""
String input = reader.readLine();
while (input != null)
{
content = content + input;
input = reader.readLine();
}
这通过将行存储在变量中并检查变量是否为 null 来避免读取然后丢弃每隔一行的问题。
每次您调用 readLine()
它都会读取下一行。语句
while (reader.readLine() != null)
读取一行但不对其执行任何操作。你要的是
String line;
StringBuilder buf;
while ( (line = reader.readLine()) != null)
{
buf.append(line);
}
content = buf.toString();
使用 StringBuilder
更好,因为它避免了每次追加时都重新分配和复制整个字符串。
谁能告诉我为什么我的代码从不读取文件的第二行?如果我在文件中的第二行(例如 .txt 文件)从一个新行开始并缩进该行,它将不会读取 it.But 如果它在一个新行中并且没有缩进,它将读取.它也可以读取第 3 行。它与 while 循环有关吗?
Scanner keyboard = new Scanner (System.in);
System.out.println("Input the file name");
String fileName = keyboard.nextLine();
File input = new File (fileName);
BufferedReader reader = new BufferedReader(new FileReader(input));
String content = reader.readLine();
content.replaceAll("\s+","");
while (reader.readLine() != null) {
content = content + reader.readLine();
}
System.out.println(content);
在下面的代码中查看我的评论。
String content = reader.readLine(); //here you read a line
content.replaceAll("\s+","");
while (reader.readLine() != null) //here you read a line (once per loop iteration)
{
content = content + reader.readLine(); //here you read a line (once per loop iteration)
}
如您所见,您正在读取 while 循环开头的第二行,并在继续之前检查它是否等于 null。但是,您对该值不做任何操作,它就丢失了。更好的解决方案如下所示:
String content = ""
String input = reader.readLine();
while (input != null)
{
content = content + input;
input = reader.readLine();
}
这通过将行存储在变量中并检查变量是否为 null 来避免读取然后丢弃每隔一行的问题。
每次您调用 readLine()
它都会读取下一行。语句
while (reader.readLine() != null)
读取一行但不对其执行任何操作。你要的是
String line;
StringBuilder buf;
while ( (line = reader.readLine()) != null)
{
buf.append(line);
}
content = buf.toString();
使用 StringBuilder
更好,因为它避免了每次追加时都重新分配和复制整个字符串。