I’m trying to read from a text files using BufferedReader. I want to skip a line that has “#” and “*” and it works. But it doesn’t work on empty line. I use line.isEmpty() but only the first ouput shows.
My text file looks like this:
# 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
My code:
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();
}
The output that i want should be like this:
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
Each call to
readline()skips one line if not assigned to a variable, just remove those calls, and since this empties most of the if-else blocks, you can simplify it to: