pel*_*ngi 1 java io text readline bufferedreader
我正在尝试使用BufferedReader从文本文件中读取.我想跳过一个有"#"和"*"的行,它可以工作.但它不适用于空行.我使用line.isEmpty()但只显示第一个输出.
我的文本文件如下所示:
# Something something
# Something something
# Staff No. 0
* 0 0 1
1 1 1 1 1 1
* 0 1 1
1 1 1 1 1 1
* 0 2 1
1 1 1 1 1 1
Run Code Online (Sandbox Code Playgroud)
我的代码:
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(folder));
try {
String line = null;
while (( line = input.readLine()) != null){
if (line.startsWith("#")) {
input.readLine();
}
else if (line.startsWith("*")) {
input.readLine();
}
else if (line.isEmpty()) { //*this
input.readLine();
}
else {
contents.append(line);
contents.append(System.getProperty("line.separator"));
System.out.println(line);
}
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我想要的输出应该是这样的:
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
Run Code Online (Sandbox Code Playgroud)
readline()如果没有分配给变量,每次调用都会跳过一行,只需删除这些调用,并且由于这会清空大多数if-else块,因此可以将其简化为:
// to be a bit more efficient
String separator = System.getProperty("line.separator");
while (( line = input.readLine()) != null)
{
if (!(line.startsWith("#") ||
line.startsWith("*") ||
line.isEmpty() ))
{
contents.append(line);
contents.append(separator);
System.out.println(line);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
723 次 |
| 最近记录: |