0

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

4

2 に答える 2

2

これを実現するには、 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);

                }
            }



    }
}
于 2013-03-05T15:05:11.637 に答える
0

あなたには必要だ !

if (newfile.exists())  

if (!newfile.exists())

また、規則に従う必要があります。そしてユニットテスト

于 2013-03-05T14:10:04.423 に答える