2016-04-05 7 views
0

現在、Javaでパッケージを作成しています。これは、クラスを作成してアウトファイルに書き込むメソッドを含んでいます。アウトファイルが存在していても作成されています

私の目標は、メソッドがアウトファイルがすでに作成されているかどうかを確認することです。そうでない場合は作成してください。それがあれば、何もしないでください。 outfileを作成することで、私は自分の条件に指定したsourceType変数を、実際のファイル名(パス全体ではない)の接頭辞として追加したいだけです。

私のチェックにもかかわらず、ファイルがまだ作成されるので、私の問題は最後の文にあります。一度実行すると、 "/ path/to/myFile"から "/ path/to// FL_myFile"が取得されます。 2回実行すると、 "/ path/to/FL_FL_myFile"という別のファイルが作成されますが、これは間違っています。

私はしばらくの間、ノンストップのプログラミングをしてきたし、私の脳は

はどうもありがとうございました...これは愚かなエラーの場合はお許し下さいかなり疲れています!答えのためのポールOstrowskiに

public static void RenameFiles(File subDir) { 
    File[] files = subDir.listFiles(); 
    Path source = FileSystems.getDefault().getPath(subDir.toString()); 
    String sourceType = null; 
    if (source.toString().endsWith("Flavonoid")) { 
     sourceType = "/FL_"; 
    } else { 
     sourceType = "/SR_"; 
    } 
    for (File file : files) { 
     Path oldFilePath = FileSystems.getDefault().getPath(file.toString()); 
     Path newFilePath = FileSystems.getDefault().getPath(subDir.toString() + sourceType + file.getName()); 
     File newFile = newFilePath.toFile(); 
     if(newFile.exists()) { 
      System.out.println("Exists!!! Do nothing! : " + newFile.toString()); 
      continue; 
     } else { 
      System.out.println("Does not exist!! Make it!! " + newFile.toString()); 
      try { 
       Files.move(oldFilePath, newFilePath); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

ありがとう:

は、ここに私のコードです。予想どおり、それはまだわかりませんでした。以下に簡単な修正を追加しました。

public static void RenameFiles(File subDir) { 
    File[] files = subDir.listFiles(); 
    Path source = FileSystems.getDefault().getPath(subDir.toString()); 
    String sourceType = null; 
    if (source.toString().endsWith("Flavonoid")) { 
     sourceType = "/FL_"; 
    } else { 
     sourceType = "/SR_"; 
    } 
    for (File file : files) { 
     Path oldFilePath = FileSystems.getDefault().getPath(file.toString()); 
     Path newFilePath = FileSystems.getDefault().getPath(subDir.toString() + sourceType + file.getName()); 
     File newFile = newFilePath.toFile(); 
     if(file.getName().startsWith("SR_") || file.getName().startsWith("FL_")) { 
      continue; 
     } else { 
      System.out.println("Creating outfile: " + newFile.toString()); 
      try { 
       Files.move(oldFilePath, newFilePath); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

答えて

1

ファイルが "FL_"または "SR_"で始まるかどうかを確認する必要はありません。最初に実行すると、foo.barの名前がFL_foo.barに変更されます。 2回目に実行すると、foo.barの名前は変更されませんが、すでに存在するFL_foo.barの名前はFL_FL_foo.barに変更されます。ファイル名が「FL_」または「SR_」で始まるかどうかを確認する必要があります。

関連する問題