문제

While reading a file with a BufferedReader, I want it to skip blank lines and lines that start with '#'. Ultimately, each individual character is then added to an arraylist

inputStream = new BufferedReader(new FileReader(filename));

       int c = 0;
       while((c = inputStream.read()) != -1) {
           char face = (char) c;

           if (face == '#') {
               //skip line (continue reading at first char of next line)
           }
           else {
               faceList.add(face);
           }

Unless I'm mistaken, BufferedReader skips blank lines automatically. Other than that, how would I go about doing this?

Would I just skip()? The length of the lines may vary, so I don't think that would work.

도움이 되었습니까?

해결책

Do not attempt to read the file a character at a time.

Read in one complete line, into a String, on each iteration of your main loop. Next, check it it matches the specific patterns you want to ignore (empty, blanks only, starting with a #, etc). Once you have a line you want to process, only then iterate over the String a character at a time if you need to.

This makes checking for and ignoring blank lines and lines matching a pattern MUCH easier.

while((line=in.readline()) != null)
{
    String temp = line.trim();
    if (temp.isEmpty() || temp.startsWith("#"))
        /* ignore line */;
    else
        ...
}

다른 팁

Use continue. This will continue to the next item in any loop.

       if (face == '#') {
           continue;
       }
       else {
           faceList.add(face);
       }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top