写入文件而不覆盖或附加 [英] Writing to a file without overwriting or appending

查看:23
本文介绍了写入文件而不覆盖或附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编写一个程序,其中的输出被写入一个 .txt 文件.每次我运行程序时,文件都会被覆盖.我不想使用追加开关并将数据添加到文件中.

I am writing a program in Java where the output is written to a .txt file. Each time I run the program the file is overwritten. I do not want to use the append switch and add data to the file.

我想要它,所以每次运行程序时都会创建一个同名的新文件.比如overflow.txt是文件名,我运行程序3次,文件overflow(1).txt,overflow(2).txtoverflow(3).txt应该做.

I would like to have it so a new file, with the same name, is created each time I run the program. For example, if overflow.txt is the file name, and I run the program three times, the files overflow(1).txt, overflow(2).txt, and overflow(3).txt should be made.

如何做到这一点?

推荐答案

先检查文件是否存在.如果是,请修改名称.

Check if the file exists first. If so, modify the name.

String origName = "overflow";
String ext = ".txt";
int num = 1;
file = new File(origName + ext);
while (file.exists()) {
 num++;
 file = new File(myOrigFileName +"(" + num + ")" + ext);
}

根据实际需要修改.问题不是很清楚.

Modify depending on actual requirements. Question is not very clear.

这篇关于写入文件而不覆盖或附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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