好问题
Good  Question
  • 首 页
  • 问题
    • PHP
    • JAVA
    • CPlusPlus
    • C#
    • SQL
  • 关 于
  • 联 系
在Java中如何将文本附加到一个已经存在的文件中 关闭 返回上一级  

在Java中如何将文本附加到一个已经存在的文件中
+ 查看更多

发布日期:2018-03-10 10:56
分类:JAVA
浏览次数:94
在Java中,我需要反复的将文本附加到一个已经存在的文件夹中。我该怎么做呢?

回答

你这样做是为了记录的目的吗?如果是这样,有一些库是解决这个问题的。其中最流行的是Log4j和Logback。
Java 7:
如果你只需要这样做一次,使用Files类会相当容易:
try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}
但是,如果你将会多次写入同一文件,上面的操作必须对磁盘上的文件进行多次打开和关闭,这是一个缓慢的操作。在这种情况下,缓冲写入更好:
try(FileWriter fw = new FileWriter("outfilename", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
使用时,需要注意以下几点:
1. FileWriter 构造函数的第二个参数意味着附加到文件上(而不是写一个新文件)。
2. 对于一个比较大的写入程序(例如FileWriter)推荐使用BufferedWriter 。
3. 使用PrintWriter ,你可以看看println语法,大多数人可能习惯使用System.out方法,但println在这里可能更合适一些。
4. BufferedWriter和PrintWriter 包装不是绝对必要的。
 
老版本的Java:
try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
异常处理:
如果你需要对老版本的Java进行必要的异常处理,代码会变得非常冗长:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}
上一篇在Java中删除字符串中的空格
在Java中如何创建一个新的List?下一篇
下一篇在Java中如何创建一个新的List?

最新文章

  • 函数`__construct`用来干嘛的
    发布日期:2018-03-26
  • 通过访客的IP得到他们的地区
    发布日期:2018-03-26
  • 合并两个PHP对象的最好的方法是什么?
    发布日期:2018-03-26
  • 该如何把一该如何把一个对象转化成数组?
    发布日期:2018-03-26
  • 什么是输出缓冲区?
    发布日期:2018-03-26
  • 在PHP中怎么把用逗号分隔的字符串分隔在一个数组里?
    发布日期:2018-03-26
  • 在PHP中使用foreach循环时查找数组的最后一个元素
    发布日期:2018-03-26
关于好问
收集整理一些有用的问题和回答,造福中国的程序旺和IT喵们!
友情链接
起飞页 
相关信息
版权声明
Copyright © 2016 - 2017  苏州卡达网络科技有限公司 好问 GOODQ.TOP 备案号:苏ICP备09008221号-5