这是用Java重写文件内容的最好方法吗? [英] Is this the best way to rewrite the content of a file in Java?

查看:908
本文介绍了这是用Java重写文件内容的最好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



到目前为止我想到的是:


  • 保存文件名称
  • 删除现有文件
  • 创建一个同名的新文件

  • 将所需内容写入空白文件

    这是最好的方法吗?还是有更直接的方法,就是不必删除和创建文件,而只是简单地改变内容?

    解决方案
  • 覆盖文件foo.log:

     文件myFoo = new File(foo.log); 
    FileOutputStream fooStream = new FileOutputStream(myFoo,false); //真的追加
    // false来覆盖。
    byte [] myBytes =New Contents \\\
    .getBytes()
    fooStream.write(myBytes);
    fooStream.close();

     文件myFoo =新文件(foo.log); 
    FileWriter fooWriter = new FileWriter(myFoo,false); //真的追加
    // false来覆盖。
    fooWriter.write(New Contents \\\
    );
    fooWriter.close();

    编辑:显示FileOutputStream和FileWriter的示例...


    I want to rewrite the contents of a file.

    What I have thought of so far is this:

    1. Save the file name
    2. Delete the existing file
    3. Create a new empty file with the same name
    4. Write the desired content to the empty file

    Is this the best way? Or is there a more direct way, that is, not having to delete and create files, but simply change the content?

    解决方案

    To overwrite file foo.log:

    File myFoo = new File("foo.log");
    FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
                                                                     // false to overwrite.
    byte[] myBytes = "New Contents\n".getBytes() 
    fooStream.write(myBytes);
    fooStream.close();
    

    or

    File myFoo = new File("foo.log");
    FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
                                                         // false to overwrite.
    fooWriter.write("New Contents\n");
    fooWriter.close();
    

    Edit: show examples of both FileOutputStream and FileWriter...

    这篇关于这是用Java重写文件内容的最好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆