[英]Java renameTo() function not moving file
我在媒體模塊中運行以下Java代碼:
File file = new File("/my/path/"+String.format("%02d", date)+"/"+streamAliasRef+".mp4");
// Destination directory
File dir = new File("/mnt/s3");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
getLogger().info("File failed to move to s3"+file.getName());
}
else {
getLogger().info("File moved to s3 successfully"+ file.getName());
}
由於某種原因,我一直在獲取“文件無法移至s3”
我對Java很陌生,所以如果這是一個簡單的問題,請原諒我。 我知道兩個目錄都存在。 可能與它有關的一個重要說明是我正在使用Fuse將S3存儲桶安裝到文件系統。
在運行於UNIX上的Java中,只有在相同文件系統中時,renameTo才有效。 因此,如果您跨文件系統移動,則需要復制和刪除原始文件。 unix mv命令也可以執行此操作。 這就是為什么mv在同一文件系統上是即時的,但在整個文件系統上卻要花很長時間的原因。 在這種情況下,它將檢測到不同的文件系統並進行副本刪除。
我從Guava使用此方法在Unix上移動文件來解決此問題:
public static void move(File from, File to) throws IOException {
Preconditions.checkNotNull(to);
Preconditions.checkArgument(!from.equals(to),
"Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
首先,您確定
new File("/my/path/"+String.format("%02d", date)+"/"+streamAliasRef+".mp4")
真的存在嗎? 您可以先嘗試使用file.exists()
進行檢查嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.