2016-10-06 1 views
0

ファイルを最初に整理して、ファイル名の番号で指定された順序に従って名前を変更したいとします。例えば番号に合わせてファイルを整理して名前を変更するにはどうすればよいですか?

私は別のファイルの束を含むフォルダを持っています。ファイル名は、最後に数字で示されます。そのフォルダに次のファイルがあるとします:

file_1.xml // Remains unchanged 
file_2.xml // Remains unchanged 
file_4.xml // Should be renamed to "file_3.xml" 
file_9.xml // Should be renamed to "file_4.xml" 
file_12.xml // Should be renamed to "file_5.xml" 

どうすればよいですか?私は、ファイルの名前を順番に変更する、信頼性の高いクリーンな方法を作りたいと考えています。

これまでのところ:

private void updateFilesName() { 
    for (int i = 1; i <= filesAmount; i++) { 
     File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); 
     File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml"); 
     if (!file1.exists() && file2.exists()) { 
      file2.renameTo(file1); 
     } 
    } 
} 

しかし、2つのファイルの位置の差が、この方法はfile_9file_12のために動作しません(file_2file_4の間のような)1だった場合にのみ動作します。

+0

リストにそれらを入れて、それらを並べ替えます。リストの名前で名前を変更します。 – ifly6

+0

OPがすでにリストをソートしているかのように見えます。伝えてください。 – greenapps

+0

あなたの例では、file_2.xmlがその名前を保持することが重要ですか?または、操作後に_1〜_5のファイル名があることに満足していますか?そして、例えば_5は_2でしたか? – greenapps

答えて

1
private void updateFilesName() { 
    int j; 
    for (int i = 1; i <= filesAmount; i++) { 
     File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); 
     if (!file1.exists()) { 
      j = i+1;  
      while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) { 
       j++; 
      } 
      (new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1); 
     } 
    } 
} 
+0

清潔でシンプル。 –

0
// Iterate all files under the directory and check the file name 
    File folder = new File("urdirectory"); 
    File[] listOfFiles = folder.listFiles(); 


    for (int i = 0; i < listOfFiles.length; i++) { 
     if (listOfFiles[i].isFile()) { 
     if (!listOfFiles[i].getName().equals("file_" + (i+1) + ".xml")) { 
      File tempFile1 = listOfFiles[i]; 
      File tempFile2 = new File("urdirectory" + "/file_" + String.valueOf(i + 1) + ".xml"); 
      tempFile.renameTo(tempFile2); 
     } 
    } 
+0

たとえば、2つのファイルがあり、そのシーケンスがfile_2.xml、file_1.xmlである場合、これは機能しません。 – greenapps

+0

残念ながら、それは私のファイルを正しく整理しませんでした。 –

+0

フセインあなたはもちろん何がうまくいかないか教えてください。 – greenapps

関連する問題