简体   繁体   English

使用BufferedReader读取Java中的.txt文件

[英]Reading .txt files in Java using BufferedReader

I'm using a BufferedReader to read a .txt files from Java but it acts strange. 我正在使用BufferedReader从Java读取.txt文件,但它的行为很奇怪。 Some files are read normally and some return few empty lines and null or skips first few lines of text and prints rest. 某些文件可以正常读取,有些则返回几行空行,并且为null或跳过文本的前几行,并打印其余部分。 I checked paths, encoding, attributes, everything is the same in those files that I'm trying to read but code read one file and other wont. 我检查了路径,编码,属性,在我尝试读取的那些文件中,所有内容都相同,但是代码读取了一个文件,而其他文件则不会。

System.out.println("\r\nChose desired shelf:");
String shelf = br.readLine();
FileReader fr = new FileReader("D:\\admir\\MyBookLibrary\\"+shelf+"\\Info.txt");
BufferedReader info = new BufferedReader(fr);
while(info.readLine() != null) {
    System.out.println(info.readLine());
}
fr.close();
info.close();

You are reading lines with readLine() twice which means you will print every second line. 您将使用readLine()两次读取行,这意味着您将每隔一行打印一次。 Also you should use try-with-resource to manage your AutoCloseable objects: 另外,您应该使用try-with-resource管理您的AutoCloseable对象:

String shelf = br.readLine();
Path path = Paths.get("D:", "admir", "MyBookLibrary", shelf, "Info.txt");
try (BufferedReader br = Files.newBufferedReader(path)) {
  br.lines().forEach(System.out::println);
}

Since your code has info.readLine() twice, it will skip printing alternate lines for all the files. 由于您的代码具有两次info.readLine() ,因此它将跳过为所有文件打印备用行。 It is possible that for files that are getting printed correctly you have an empty line or linefeed character \\n after each line of text, and coincidently that is being skipped. 对于可能正确打印的文件,您可能在每行文本后都有一个空行或换行符\\n ,这恰好被跳过了。 In the other files also, it must be skipping alternate lines. 同样在其他文件中,它也必须跳过替代行。 Can you check the actual content of your files. 您可以检查文件的实际内容吗?

I have modified your code slightly and it works now: 我已经稍微修改了您的代码,现在可以使用:

System.out.println("\r\nChose desired shelf:");
String shelf = br.readLine();
FileReader fr = new 
FileReader("D:\\admir\\MyBookLibrary\\"+shelf+"\\Info.txt");
BufferedReader info = new BufferedReader(fr);
String line;
while((line = info.readLine()) != null) {
    System.out.println(line);
}
fr.close();
info.close();

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

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