开发者

Rename an existing file or pdf using JAVA its fails

开发者 https://www.devze.com 2023-03-17 18:29 出处:网络
String fileOne = \"C:/1236.pdf\"; String fileTwo = \"C:/22.pdf\"; String mergedFileLocation = \"C:/myMergedData.pdf\";

String fileOne = "C:/1236.pdf";

String fileTwo = "C:/22.pdf";

String mergedFileLocation = "C:/myMergedData.pdf";

if (new File(mergedFileLocation).renameTo(new File(fileOne))) {

// rename successful } else {

// rename has failed }

after the merging is done

rename an existing file

so i need to delete the fileOne first later i guess i need to rename

i need to rename and replacing the mergedFileLocation equals to fileOne

开发者_JS百科

i.e., myMergedData.pdf to 1236.pdf


Delete the old file first.

File f = new File(fileOne);
if (f.delete() && new File(mergedFileLocation).renameTo(f)) { 
    //successfully renamed
}


Your attempt to rename a file using a filename which already exists will fail. You will have to delete or rename the old file first.

  public static void main(String[] args) throws IOException {

    File workingDir = new File(".");
    File fileOne = new File("1236.pdf");
    File mergedFile = new File("myMergedData.pdf");

    fileOne.createNewFile();
    mergedFile.createNewFile();

    FilenameFilter filter = new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return name.endsWith(".pdf");
      }
    };

    String[] list = workingDir.list(filter);
    System.err.println(Arrays.asList(list));

    if (fileOne.isFile()) {
      // delete or rename
      if (fileOne.delete()) {
        // deleted successfully
      }
    }

    list = workingDir.list(filter);
    System.err.println(Arrays.asList(list));

    if (mergedFile.renameTo(fileOne)) {
      // renamed successfully
    } else {
      // rename failed
    }

    list = workingDir.list(filter);
    System.err.println(Arrays.asList(list));

  }

The output is

[1236.pdf, myMergedData.pdf]
[myMergedData.pdf]
[1236.pdf]
0

精彩评论

暂无评论...
验证码 换一张
取 消