我的代码在逻辑上出了什么问题?
我正在编写重命名java文件数的代码。我有一个.txt
中的文件列表。我的程序在其中检索文档名称及其新名称的文件。它目前不工作..它编译和运行,但它不会重命名我的文件。我的代码在逻辑上出了什么问题?
这里是我的代码:
public static void rename(String ol, String ne){
File oldfile =new File(ol);
File newfile =new File(ne);
int t=0;
if(oldfile.isFile() && oldfile.canRead()){
if (newfile.exists()){
t++;
ne = ne.substring(0,ne.lastIndexOf('.')) + " (" + t + ")" +
ne.substring(ne.lastIndexOf('.')) ;
rename(ol,ne);
}
if(oldfile.renameTo(newfile))
System.out.println("Rename succesful");
else
System.out.println("Rename failed" + " - " + ol + " " + ne);
}else
System.out.println("CANNOT Rename " + oldfile + " because read/write issues. Check
if File exists");
}
public static void main(String[] args) throws IOException
{
ReadFile ren = new ReadFile("List of Founds.txt");
String r[] = ren.OpenFile();
for(int j=0; j<ReadFile.numberOfLines; j++){
String pdfOldName = r[j].substring(0,r[j].lastIndexOf('.'));
String pdfNewName = r[j].substring((r[j].lastIndexOf('.') + 4));
rename(pdfOldName, pdfNewName);
}
}
这是.txt
文件“创立的名单”,老字号是在左边,新名称在右边。
test.pdf.txt ayo1
test2.pdf.txt ayo2
test3.pdf.txt ayo3
您可以使用File.html#renameTo(java.io.File)来完成此操作。
继承人我写了一个快速示例程序。 希望这可以让你在正确的方向
public class FileMain {
static int i = 1;
public static void main(String[] args) throws Exception {
File file1 = new File("D:/workspace/dir");
renamefiles(file1);
}
private static void renamefiles(File file){
File files[] = file.listFiles();
for(File tempFile :files){
if(tempFile.isDirectory()){
renamefiles(tempFile);
}else{
System.out.println(tempFile.getName());
File renameFile = new File("sample-"+(++i)+".bck");
tempFile.renameTo(renameFile);
}
}
}
}
感谢Sudhakar,您的代码可以创造奇迹。我会尝试修改它以满足我的需求。再次感谢 – 2013-03-06 09:42:45
Upvote和绿剔分享你的喜悦:)干杯 – Sudhakar 2013-03-06 10:26:19
感谢您的回应将但将条件newfile.exists()更改为!newfile.exists()没有解决问题。 – 2013-03-05 14:23:13
你可以发布你的程序运行时会发生什么? – JohnnyO 2013-03-05 14:10:16
它让我'重命名失败'。多数民众赞成在第6行的其他部分... ... – 2013-03-06 09:45:06