合并完成后String fileOne =“C:/1236.pdf”;
String fileTwo =“C:/22.pdf”;
String mergedFileLocation =“C:/myMergedData.pdf”;
if(new File(mergedFileLocation).renameTo(new File(fileOne))){
//重命名成功}其他{
//重命名失败}
重命名现有文件
所以我需要先删除fileOne,我想我需要重命名
我需要重命名并将mergedFileLocation替换为fileOne
即, myMergedData.pdf至1236.pdf
答案 0 :(得分:0)
您尝试使用已存在的文件名重命名文件将失败。您必须先删除或重命名旧文件。
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));
}
输出
[1236.pdf, myMergedData.pdf]
[myMergedData.pdf]
[1236.pdf]
答案 1 :(得分:0)
首先删除旧文件。
File f = new File(fileOne);
if (f.delete() && new File(mergedFileLocation).renameTo(f)) {
//successfully renamed
}