Java 我的代码逻辑上有什么错误?
我正在编写一个代码来重命名java中的文件数量。我在Java 我的代码逻辑上有什么错误?,java,file-rename,Java,File Rename,我正在编写一个代码来重命名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() &&
.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);
}
}
公共静态无效重命名(字符串ol,字符串ne){
文件oldfile=新文件(ol);
文件newfile=新文件(ne);
int t=0;
if(oldfile.isFile()&&oldfile.canRead()){
if(newfile.exists()){
t++;
ne=ne.子字符串(0,ne.lastIndexOf('.')+“(“+t+”)”+
ne.子串(ne.lastIndexOf('.');
重命名(ol,ne);
}
if(oldfile.renameTo(newfile))
System.out.println(“重命名成功”);
其他的
System.out.println(“重命名失败”+“-”+ol+”+ne);
}否则
System.out.println(“由于读/写问题,无法重命名”+oldfile+”。请检查
如果文件存在”);
}
公共静态void main(字符串[]args)引发IOException
{
ReadFile ren=new ReadFile(“List of Founds.txt”);
字符串r[]=ren.OpenFile();
对于(int j=0;j你需要一个
if (newfile.exists())
到
您还需要。并且。您可以使用来完成此操作
这是我写的一个快速示例程序。
希望这能帮你找到正确的方向
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);
}
}
}
}
你能发布程序运行时发生的事情的输出吗?它会让我“重命名失败”。这是第6行的其他部分…谢谢你的回答,但是将条件newfile.exists()更改为!newfile.exists()并没有解决问题。谢谢Sudhakar,你的代码工作得很好。我会尝试修改它以满足我的需要。再次感谢
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);
}
}
}
}