Rename file onto another in java

后端 未结 5 1958
迷失自我
迷失自我 2021-01-15 03:26

I have a file I need to rename to that of an existing file. This is a copy, modify, replace original operation on an existing JAR file. I\'ve got the first two steps done, I

相关标签:
5条回答
  • 2021-01-15 03:35

    You're going to need to create two java.io.File objects: one for the new file, one for the old file.

    Lets call these oldFile and newFile.

    oldFile.delete()
    newFile.renameTo(oldFile);
    

    Edit: mmyers beat me to it.

    0 讨论(0)
  • 2021-01-15 03:36

    This should get you reasonably close:

    public boolean replaceOldJar(String originalJarPath, java.io.File newJar) {
        java.io.File originalJar = new java.io.File(originalJarPath);
        if (!originalJar.isFile()) {
            return false;
        }
        boolean deleteOldJarSucceeded = originalJar.delete();
        if (!deleteOldJarSucceeded) {
            return false;
        }
        newJar.renameTo(originalJar);
        return originalJar.exists();
    }
    
    0 讨论(0)
  • 2021-01-15 03:44

    I'm not completely sure if you are asking simply how to rename the file in the filesystem or if you also want to reload this new version of your jar?

    The rename part sounds easy... just use File.renameTo... unfortunately, there are many platform specific problems related to doing this. Some platforms will not allow you to overwrite an existing file, others will not allow you to rename a file so it changes location onto another partition. If you want to make the process completely safe, you need to do the process yourself by removing the old file first and then renaming the new (or copying if a partition change is possible). This is naturally prone to problems if your application/machine crashes while doing this, since it is no longer an atomic operation. You will thus need to add a check to your applications startup process that looks for rename operations that were in the middle when the crash occured. If you are just updating a single file in this way, it should be pretty easy.

    However, if you actually want to reload the jar, there are a few more issues to thing about, but you would need to give a bit more detailed view of the situation to get proper advice on how to do it.

    0 讨论(0)
  • 2021-01-15 03:56

    Java.io.File.renameTo(java.io.File)

    You might need to call File.delete() first on the original file first - some systems won't rename a file onto an existing file.

    0 讨论(0)
  • 2021-01-15 03:59

    Is there a problem with deleting the old one and renaming the new one?

    0 讨论(0)
提交回复
热议问题