栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在java中如何追加文本到存在的文件中?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在java中如何追加文本到存在的文件中?

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}

注意:NoSuchFileException如果文件不存在,上述方法将抛出。它还不会自动追加换行符(追加到文本文件时通常会需要此换行符)。

但是,如果你要多次写入同一文件,则上述操作必须多次打开和关闭磁盘上的文件,这是一个缓慢的操作。在这种情况下,使用缓冲写入器更好:

try(FileWriter fw = new FileWriter("myfile.txt", true);    BufferedWriter bw = new BufferedWriter(fw);    PrintWriter out = new PrintWriter(bw)){    out.println("the text");    //more pre    out.println("more text");    //more pre} catch (IOException e) {    //exception handling left as an exercise for the reader}

笔记:

  • FileWriter
    构造函数的第二个参数将告诉它追加到文件中,而不是写入新文件。(如果文件不存在,将创建它。)
  • BufferedWriter
    对于昂贵的作家(例如
    FileWriter
    ),建议使用。
  • 使用a
    PrintWriter
    可访问
    println
    你可能习惯使用的语法
    System.out
  • 但是
    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    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369089.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号