我应该在班级客户端使用try-with-resources吗?

时间:2015-02-21 20:38:16

标签: java resources java-7 try-with-resources

我有两个班级:

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());
        }
    }
}

我应该在Main类中使用try-with-resources吗?或者我如何在Main类中关闭资源?

0 个答案:

没有答案