[英]How to specify a new name for a file while moving it to another directory in Java?
Apache Commons IO
有一種將文件移動到另一個目錄的方法,該方法不允許我在目標目錄中為其指定新名稱:
public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)
throws IOException
我不想先重命名文件,然后再將文件移到另一個目錄。 有任何方法可以通過任何庫方法中的單個語句來執行此操作嗎? (我想要一個方法以避免任何並發問題,該問題將由庫自動處理)
從Java7開始,您可以使用Files.move 。 例如
Path source = Paths.get(src);
Path target = Paths.get(dest);
Files.move(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);
Apache Commons IO FIleUtils類具有moveFile方法。 您只需要在destFile
參數中指定“新名稱”即可。
FileUtils.moveFile(
FileUtils.getFile("src/test/old-resources/oldname.txt"),
FileUtils.getFile("src/test/resources/renamed.txt"));
正如伊恩·羅伯茨(Ian Roberts)在回答中正確說的那樣,如果您知道目的地存在,則可以在文件上使用srcFile.renameTo(destFile)
方法,但是Commons IO類將為您執行檢查/文件夾創建。 如果無論什么原因renameTo失敗(返回false), 它將在后台使用FileUtils自己的copyFile方法。 如果我們查看方法注釋,則會清楚地看到“如果沒有目標目錄,則創建包含目標文件的目錄”。
這是FileUtils moveFile方法的源代碼,因此您可以清楚地看到它為您提供的功能:
2943 public static void moveFile(final File srcFile, final File destFile) throws IOException {
2944 if (srcFile == null) {
2945 throw new NullPointerException("Source must not be null");
2946 }
2947 if (destFile == null) {
2948 throw new NullPointerException("Destination must not be null");
2949 }
2950 if (!srcFile.exists()) {
2951 throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
2952 }
2953 if (srcFile.isDirectory()) {
2954 throw new IOException("Source '" + srcFile + "' is a directory");
2955 }
2956 if (destFile.exists()) {
2957 throw new FileExistsException("Destination '" + destFile + "' already exists");
2958 }
2959 if (destFile.isDirectory()) {
2960 throw new IOException("Destination '" + destFile + "' is a directory");
2961 }
2962 final boolean rename = srcFile.renameTo(destFile);
2963 if (!rename) {
2964 copyFile( srcFile, destFile );
2965 if (!srcFile.delete()) {
2966 FileUtils.deleteQuietly(destFile);
2967 throw new IOException("Failed to delete original file '" + srcFile +
2968 "' after copy to '" + destFile + "'");
2969 }
2970 }
2971 }
來源: http : //commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#moveFile(java.io.File,java.io.File)
如果您知道目標目錄已經存在,那么您不需要外部任何內容,只需使用srcFile.renameTo(destFile)
-源文件和目標文件不必位於同一目錄中。
Apache Common具有許多有用的方法。 例如,您可以使用以下代碼:
public void moveMyFile throws IOException {
FileUtils.moveFile(
FileUtils.getFile("path/to/source.txt"),
FileUtils.getFile("path/to/new destination.txt"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.