zoukankan      html  css  js  c++  java
  • 文件的读取与保存(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优雅关闭

  • 相关阅读:
    Linux-CentOS6.9启动流程排错
    jenkins+maven+svn 自动化部署
    Linux下Mysql5.6 二进制安装
    es的api
    es的QueryBuilder学习使用
    es的QueryBuilders使用
    安装vue的开发环境
    自定义组件
    mounted钩子函数,页面初始化完成此函数加载
    双亲委派机制
  • 原文地址:https://www.cnblogs.com/excellencesy/p/11306742.html
Copyright © 2011-2022 走看看