0

I have two classes:

public class FileMessageReader {
    private final String messageFilePath;

    public FileMessageReader(String filePath) throws FileNotFoundException {
        //...
        messageFilePath = filePath;
    }

    public int getNumberOfMessages() throws IllegalMessageFormatException, IOException {
        try (FileReader file = new FileReader(messageFilePath);
             BufferedReader reader = new BufferedReader(file)) {

            String line;

            while ((line = reader.readLine()) != null) {
                //work with line
            }

        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("file" + messageFilePath + " not found.");
        } catch (IOException e) {
            throw new IOException("Strange IOException happened. Message: " + e.getMessage());
        }

        return numberOfMessages;
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            FileMessageReader fileMessageReader = new FileMessageReader(args[0]);
            int numberOfMessages = fileMessageReader.getNumberOfMessages();
            //////

        } catch (IllegalMessageFormatException | IOException e){
            System.out.println(e.getMessage());
        }
    }
}

Should I use try-with-resources in Main class? Or how I have to close resource in Main class?

Denis
  • 3,595
  • 12
  • 52
  • 86
  • There's nothing in the code you posted that could leak. The `FileReader` is already opened in a try-with-resources, so it will be closed. Also, there's no need to catch and rethrow `FileNotFoundException` or `IOException`. – Steve McKay Feb 21 '15 at 20:45
  • Except your BufferedReader, which should be included in the opening try. Your FileMessageReader doesn't implement Closable, so it can't be included in the try-with-resources – MadProgrammer Feb 21 '15 at 20:51
  • @MadProgrammer, about what `BufferedReader` do you say? I see only one `BufferedReader`, which is included in the try block. – Denis Feb 21 '15 at 20:56
  • 1
    You could also add throws to main and remove all catches – Oleg Mikheev Feb 21 '15 at 20:57
  • @MadProgrammer, I thought, that `BufferedReader` will be closing too - http://stackoverflow.com/a/21348893/1756750 Am I wrong? – Denis Feb 21 '15 at 21:13
  • 1
    Yeah, it is, I was reading it on my ipad and the `BufferedReader` looked like it was declared outside of the `try(...)` – MadProgrammer Feb 21 '15 at 21:14

0 Answers0