Writing to a file without overwriting or appending

僤鯓⒐⒋嵵緔 提交于 2019-12-02 13:23:23

Check if the file exists, if so rename it. Using File.exists and FileUtils.moveFile

You would need to do this recursively until no conflict is found.

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.

"A new file with the same name" doesn't make sense in most file systems.

In your example, you've got three files with different names:

  • overflow(1).txt
  • overflow(2).txt
  • overflow(3).txt

The bit in brackets is still part of the name. If you want to emulate that behaviour, you'll have to:

  • Detect the presence of the "plain" filename (if you want to write to that if it doesn't exist)
  • Start counting at 1, and work out the "new" filename each time by removing the extension, adding the count in brackets, then putting the extension back
  • Keep counting until you find a filename which doesn't exist
String dirPath = "./";
String fileName = dirPath + "overflow.txt";
if(new File(dirPath + fileName).exist())
{
    int counter = 0;
    while(new File(dirPath + "overflow(" + ++counter + ").txt").exist());
    fileName = "overflow(" + counter + ").txt";
}

When you instanciate the File object, verify if it exists, if it does, just rename it by adding the braces and number, and check again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!