文件的读取与保存(try-with-resource优雅关闭)

借鉴:https://www.cnblogs.com/itZhy/p/7636615.html

一、背景

在Java编程过程中,如果打开了外部资源(文件、数据库连接、网络连接等),我们必须在这些外部资源使用完毕后,手动关闭它们。如果我们不在编程时确保在正确的时机关闭外部资源,就会导致外部资源泄露,紧接着就会出现文件被异常占用,数据库连接过多导致连接池溢出等诸多很严重的问题。

二、传统的方式

1、读文件

    /**
     * 获取指定文件的内容
     * @param filePath 文件的路径
     * @return 文件的内容
     */
    public static String getSingleCon(String filePath) {
        File file = new File(filePath);
        InputStreamReader read = null;
        String content = "";
        try {
            read = new InputStreamReader(new FileInputStream(file), "utf-8");
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    content = content +lineTxt +"
";
                }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(read!=null){
                    read.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

2,写文件

    /**
     * 保存修改的文件
     * @param filepath 文件的位置
     * @param fileContent 文件的内容
     * @return
     */
     public static boolean saveFile(String filepath,String content,String encoding){
            boolean flag=false;
            FileOutputStream fileOutputStream=null;
            try {
                fileOutputStream = new FileOutputStream(new File(filepath));
                fileOutputStream.write(content.getBytes(encoding));
                fileOutputStream.close();
                flag=true;
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(fileOutputStream!=null){
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return flag;
        }

 二、try-with-resource优雅关闭

原文地址:https://www.cnblogs.com/excellencesy/p/11306742.html