我正在使用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.
最佳答案
我认为您的removeWhiteSpaces(i + 1, text);
有问题,如果您在字符串处理过程中有问题,读者将无法阅读下一行。
您不检查空字符串,而是调用text.charAt(text.length()-1)
,这也是一个问题。
打印异常,更改您的catch块以写出异常:
} catch (Exception e) {
e.printStackTrace();
}
原因是在您的
while(text.charAt(j) == ' ') {
中,您没有检查StringBuilder的长度,但是将其删除了...