How do I close a file after catching an IOException in java?

后端 未结 7 1262
独厮守ぢ
独厮守ぢ 2021-01-05 08:07

All,

I am trying to ensure that a file I have open with BufferedReader is closed when I catch an IOException, but it appears as if my BufferedReader object is out o

7条回答
  •  無奈伤痛
    2021-01-05 08:09

    It's better not to deal with null - the general idiom for resource acquisition and release in Java is :

    final Resource resource = acquire();
    try { use(resource); }
    finally { resource.release(); }
    

    so:

    public static List readFiletoArrayList(String fileName,
            List fileArrayList, String charsetName) {
        fileArrayList.clear(); // why fileArrayList.removeAll(fileArrayList) ?
        try {
            InputStream file = new FileInputStream(fileName);
            try {
                InputStreamReader reader = new InputStreamReader(file, charsetName);
                BufferedReader buffer = new BufferedReader(reader);
                for (String line = buffer.readLine(); line != null; line = buffer
                        .readLine()) {
                    fileArrayList.add(line);
                }
            } finally {
                try {
                    file.close();
                } catch (IOException e) {
                    e.printStackTrace(); // you do not want this to hide an
                    // exception thrown earlier so swallow it
                }
            }
        } catch (IOException e) {
            fileArrayList.clear(); // returned empty. Dealt with in client
        }
        return fileArrayList;
    }
    

    See my points here

    If you are using a reader you must specify the encoding as I am doing here. If you want to read bytes forget about the reader. Also if you use readLine() you must forget about the end of line characters - if this is a concern consider omitting the BufferedReader entirely.

提交回复
热议问题