-2

It's been a while since I code in java and I'm having trouble trying to read a plain text file. Here's my code

private static ArrayList<String> readDict() {
                BufferedReader br;
                ArrayList<String> out = new ArrayList<String>();
                try {
                        br = new BufferedReader(new FileReader("dict5.txt"));
                        String line;
                        while ((line = br.readLine()) != null) {
                                out.add(line);
                        }
                } catch(Exception exc) {
                        System.out.println("Exception catched while reading file: " + exc);
                } finally {
                        try {if (!br.isNull()) br.close();} catch(IOException exc) { System.out.println("IOException catched while closing file" + exc); }
                }
                return out;
        }

br.isNull() gives me a compilation error, do you know why this is? Thank you in advance. The error: Main.java:30: error: cannot find symbol try {if (!br.isNull()) br.close();} catch(IOException exc) { System.out.println("IOException catched while closing file" + exc); } ^ symbol: method isNull() location: variable br of type BufferedReader 1 error error: compilation failed

Landor3000
  • 21
  • 4

1 Answers1

1

IsNull is not a thing in Java. Maybe you're thinking of Ruby. In Java you can't call instance methods on a null reference, there is no isNull method. That explains the compile error.

Use try-with-resources syntax to close the reader. That way you don't have to catch the exception thrown on close separately, but you don't have to worry about the exception thrown on close masking an exception thrown in the try block. For more on try with resources see Try With Resources vs Try-Catch

Let the IOException be thrown, handle it at a higher level where you can do something useful with it. That's why we have exceptions; the place where an error occurs is not usually the place that knows what to do about it.

        ArrayList<String> out = new ArrayList<String>();
        try ( BufferedReader br = new BufferedReader(new FileReader("dict5.txt"))) {
                String line;
                while ((line = br.readLine()) != null) {
                        out.add(line);
                }
         }
            
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276