java重写文件_这是用Java重写文件内容的最佳方法吗?

这是用Java重写文件内容的最佳方法吗?

我想重写文件的内容。

到目前为止,我想到的是:

保存文件名

删除现有文件

用相同的名称创建一个新的空文件

将所需内容写入空文件

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

Ankur asked 2020-07-22T10:10:10Z

7个解决方案

81 votes

要使用FileOutputStream覆盖文件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();

或使用FileWriter:

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();

Stobor answered 2020-07-22T10:10:30Z

12 votes

我强烈建议为此使用Apache Common的FileUtil。 我发现此程序包非常宝贵。 它很容易使用,同样重要的是,稍后再返回时,易于阅读/理解。

//Create some files here

File sourceFile = new File("pathToYourFile");

File fileToCopy = new File("copyPath");

//Sample content

org.apache.commons.io.FileUtils.writeStringToFile(sourceFile, "Sample content");

//Now copy from source to copy, the delete source.

org.apache.commons.io.FileUtils.copyFile(sourceFile, fileToCopy);

org.apache.commons.io.FileUtils.deleteQuietly(sourceFile);

可以在以下位置找到更多信息:[http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html]

jnt30 answered 2020-07-22T10:10:54Z

5 votes

请参阅:java.io.RandomAccessFile

您将要打开一个读写文件,因此:

RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw");

String tmp;

while (tmp = raf.readLine() != null) {

// Store String data

}

// do some string conversion

raf.seek(0);

raf.writeChars("newString");

drfloob answered 2020-07-22T10:11:19Z

2 votes

除非您只是在最后添加内容,否则这样做是合理的。 如果要追加,请尝试使用append构造函数进行FileWriter。

更好的顺序是:

生成新文件名(例如foo.txt.new)

将更新的内容写入新文件。

从foo.txt.new原子重命名为foo.txt

不幸的是,不能保证namedTo可以进行原子重命名。

Matthew Flaschen answered 2020-07-22T10:12:00Z

1 votes

在下面的示例中,“ false”会导致文件被覆盖,true会导致相反的情况。

File file=new File("C:\Path\to\file.txt");

DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));

String body = "new content";

outstream.write(body.getBytes());

outstream.close();

Sev answered 2020-07-22T10:12:21Z

1 votes

有时候,您可能希望保留一个巨大的空文件,以避免操作系统根据需要分配空间的额外费用。 通常,这是通过数据库,虚拟机以及在处理和写入批量数据的批处理程序中完成的。 这将大大提高应用程序的性能。 在这些情况下,编写新文件并重命名实际上并没有帮助。 相反,将必须填充空文件。 那就是当必须进入超控模式的时候。

Lakshmi answered 2020-07-22T10:12:41Z

1 votes

Guava File.write“使用字节数组的内容覆盖文件”:

Files.write(bytes, new File(path));

Vadzim answered 2020-07-22T10:13:02Z

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值