现在有两个文件
001.jpg
002.jpg
想让001.jpg改名为002.jpg,同时改名002.jpg为001.jpg。
因为我不懂JAVA,麻烦给写个函数能够实现上述的功能。
方法为先将001.jpg改名为001bak.jpg,然后改名002.jpg为001.jpg,然后将001bak.jpg改为002.jpg
当文件不存在的时候需要判断一下,然后返回false。改名成功了,返回true。
谢谢
求给出代码
public static boolean exchangeName(String filePath1,String filePath2){
File file1 = new File(filePath1);
File file2 = new File(filePath2);
if(!file1.isFile() && !file1.exists())
return false;
if(!file2.isFile() && !file2.exists())
return false;
String fileName1 = file1.getName();
String fileName2 = file2.getName();
String newPath1 = filePath1.substring(0, filePath1.lastIndexOf(fileName1))+fileName2;
String newPath2 = filePath2.substring(0, filePath2.lastIndexOf(fileName2))+fileName1;
boolean resut1 = file1.renameTo(new File(newPath1));
boolean resut2 = file2.renameTo(new File(newPath2));
return resut1 & resut2;
}
import java.io.File;
public class TF {
public static void main(String[] args) {
String path1 = "c:\001.txt";
File file = new File(path1);
String name = file.getName();
String fileName = name.substring(0, name.lastIndexOf("."));
String hozui = name.substring(name.lastIndexOf("."),name.length());
String newName = path1.substring(0,path1.lastIndexOf("\")+1)+fileName+"bak"+hozui;
System.out.println(newName);
File f = new File(newName);
file.renameTo(f);
}
}