0

Below is a solution from Number of lines in a file in Java to quickly count the number of lines in a text file.

However, I am trying to write a method that will perform the same task without throwing an 'IOException'.

Under the original solution is my attempt to do this with a nested try-catch block <-- (Is this usually done/frowned upon/ or easily avoidable??) which returns 0 no matter how many lines are in the given file (obviously a fail).

Just to be clear, I am not looking for advice on how to better use the original method that does contain the exception and, therefore, the context within which I am using it is irrelevant to this question.

Can somebody please help me write a method that counts the number of lines in a text file and does not throw any exceptions? (In other words, deals with potential errors with a try-catch.)

Original line counter by martinus:

public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

My Attempt:

public int countLines(String fileName ) {
   InputStream input = null;
        try{
        try{
            input = new BufferedInputStream(new FileInputStream(fileName));
            byte[] count = new byte[1024];
            int lines = 0;
            int forChar;
            boolean empty = true;
            while((forChar = input.read(count)) != -1){
                empty = false;
                for(int x = 0; x < forChar; x++){
                    if(count[x] == '\n'){
                        lines++;
                    }
                }
            }
            return (!empty && lines == 0) ?  1 : lines + 1;
        }
        finally{
            if(input != null)
            input.close();
        }
        }
        catch(IOException f){
            int lines = 0;
            return lines;
        }
    }
Community
  • 1
  • 1
Dziugas
  • 1,500
  • 1
  • 12
  • 28

2 Answers2

0

It is more robust to use char instead of byte for '\n' and return -1 in case of any errors, for example if the filename does not exist:

    public static int countLines(String filename) {
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
        char[] c = new char[1024];
        int count = 0;
        int readChars = 0;
        boolean emptyLine = true;
        while ((readChars = br.read(c)) != -1) {
            for (int i = 0; i < readChars; ++i) {
                emptyLine = false;
                if (c[i] == '\n') {
                    ++count;
                    emptyLine = true;
                }
            }
        }
        return count + (!emptyLine ? 1 : 0);
    } catch (IOException ex) {
        return -1;
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (IOException e) {
                // Ignore intentionally
            }
    }
}
Amir Moghimi
  • 1,391
  • 1
  • 11
  • 19
-1

Sharing my attempt.

public static int countLines(String filename) {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    int numLines = 0;
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        numLines = (count == 0 && !empty) ? 1 : count;
    } catch (IOException ex) {
        numLines = 0;
    } catch (FileNotFoundException ex) {
        System.out.println("File not found.");
        numLines = 0;
    } finally {
        is.close();
    }
    return numLines;
}
Alvin Magalona
  • 771
  • 3
  • 13