爪哇 - BufferedReader中的readLine终止阅读时encouters空字符串

问题描述 投票:0回答:6

我使用的BufferedReader读取由行的文本文件一行。然后我使用的方法归一化每个行文本。但有什么毛病我的归一化方法,调用它后,BufferedReader类对象停止读取文件。有人可以帮我弄这个吗。

这里是我的代码:

public static void main(String[] args) {
    String string = "";

    try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
        String line;
        while ((line = br.readLine()) != null) {

            string += normalize(line);

        }
    } catch (Exception e) {

    }
    System.out.println(string);
}

public static String normalize(String string) {

    StringBuilder text = new StringBuilder(string.trim());



    for(int i = 0; i < text.length(); i++) {
        if(text.charAt(i) == ' ') {
            removeWhiteSpaces(i + 1, text);
        }
    }

    if(text.charAt(text.length() - 1) != '.') {
        text.append('.');
    }

    text.append("\n");
    return text.toString();
}

public static void removeWhiteSpaces(int index, StringBuilder text) {
        int j = index;
        while(text.charAt(j) == ' ') {
            text.deleteCharAt(j);
        }
    }

这里是我使用的文本文件:

abc .

 asd.



 dasd.
java file bufferedreader readline
6个回答
3
投票

我想你在removeWhiteSpaces(i + 1, text);有问题,如果您在字符串过程中有问题,读者不会能够读取下一行。

你不检查空字符串,并调用text.charAt(text.length()-1),这是一个问题了。

打印异常,改变你的catch块写出来的异常:

} catch (Exception e) {
    e.printStackTrace();
}

原因是在你的while(text.charAt(j) == ' ') {,你不检查的StringBuilder的长度,但你删除它...


1
投票

尝试这个:

   while ((line = br.readLine()) != null) {
        if(line.trim().isEmpty()) {
            continue;
        }
         string += normalize(line);
      }

1
投票

尝试ScanReader

 Scanner scan = new Scanner(is);
 int rowCount = 0;
 while (scan.hasNextLine()) {
             String temp = scan.nextLine();

             if(temp.trim().length()==0){
                 continue;
             }
}

//你的逻辑休息


1
投票

正规化功能是导致此。以下的调整它应该解决这个问题:

public static String normalize(String string) {

        if(string.length() < 1) {
            return "";
        }
        StringBuilder text = new StringBuilder(string.trim());
        if(text.length() < 1){
            return "";
        }


        for(int i = 0; i < text.length(); i++) {
            if(text.charAt(i) == ' ') {
                removeWhiteSpaces(i + 1, text);
            }
        }

        if(text.charAt(text.length() - 1) != '.') {
            text.append('.');
        }

        text.append("\n");
        return text.toString();
    }

1
投票

这个问题是不是在你的代码,但在readLine()方法的理解。在本文档中指出:

读取文本行。的线被认为是由一个换行(“\ n”)中的任何一个被终止,回车(“\ r”),或回车一个换行符紧跟。

https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

因此,这意味着,如果该方法找到一个空行,它将停止阅读并返回null

通过@ tijn167提出的代码将使用BufferedReader做的解决方法。如果你不节制地使用BufferedReader作为ScanReader瑞里@Abhishek建议。

此外,虽然空行不是空白而是位反馈removeWhiteSpaces()或换行符\r或两者的方法\n为空格检查。所以,你的条件text.charAt(j) == ' '是永远不会满足。


-1
投票

文件的第二行是空的,因此while循环停止

© www.soinside.com 2019 - 2024. All rights reserved.