博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文件的读取与保存(try-with-resource优雅关闭)
阅读量:4363 次
发布时间:2019-06-07

本文共 2152 字,大约阅读时间需要 7 分钟。

借鉴:

 

一、背景

 

在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 +"\r\n";                }        } 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

你可能感兴趣的文章
5.Joint Probability Distributions and Random Samples
查看>>
SharePoint 数据迁移解决方案
查看>>
聊聊markdown编辑器——Editor.md
查看>>
全局安装与本地安装
查看>>
汉子转拼音
查看>>
Linux下配置GitHub
查看>>
Spring AOP之Introduction(@DeclareParents)简介
查看>>
清理右键多余快捷
查看>>
asyncio 学习
查看>>
吴裕雄 python 神经网络——TensorFlow 花瓣分类与迁移学习(2)
查看>>
selenium3+python3.6爬页面源码的代码
查看>>
JAVA实现简单分组算法
查看>>
Eclipse设置
查看>>
第十一周作业
查看>>
Linux常用命令
查看>>
Eclipse.ini参数设置
查看>>
《剑指offer》第七题(重要!重建二叉树)
查看>>
【Uvalive 5834】 Genghis Khan the Conqueror (生成树,最优替代边)
查看>>
郁闷,是说linux装不上了,结果是硬盘出现坏到了~~~!
查看>>
[导入]Ubuntu 6.10 Beryl 爱你真的好难
查看>>