問了這個問題,已經在堆疊上的其他問題中嘗試了可能的解決方案,但這并沒有讓我解決問題。
如標題所示,我創建了一個 java 實用程式,我必須使用它對文本檔案執行操作,特別是我必須執行簡單的操作來在目錄之間移動、從一個目錄復制到另一個目錄等。
為此,我使用了 java 庫java.io.File和java.nio.*,并且我現在已經實作了兩個功能,copyFile(sourcePath, targetPath)以及moveFile(sourcePath, targetPath). 為了開發這個,我使用的是 mac,檔案在源路徑下/Users/myname/Documents/myfolder/F24/archive/,我的目標路徑是/Users/myname/Documents/myfolder/F24/target/.
但是當我運行我的代碼時,我得到一個 java.nio.file.NoSuchFileException: /Users/myname/Documents/myfolder/F24/archive
在堆疊和 Java 檔案中嘗試了其他解決方案后,我還沒有解決這個問題......我接受任何建議或建議
謝謝你們
- 我的代碼:
// copyFile: funzione chiamata per copiare file
public static boolean copyFile(String sourcePath, String targetPath){
boolean fileCopied = true;
try{
Files.copy(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
}catch(Exception e){
String sp = Paths.get(sourcePath) "/";
fileCopied = false;
System.out.println("Non posso copiare i file dalla cartella " sp " nella cartella " Paths.get(targetPath) " ! \n");
e.printStackTrace();
}
return fileCopied;
}
uj5u.com熱心網友回復:
Files.copy無法復制整個目錄。您傳遞給的第一個“路徑”Files.copy必須全部:
- 存在。
- 可由運行 JVM 的行程讀取。這在 mac 上很重要,默認情況下,它幾乎拒絕所有應用程式的所有磁盤權限,直到您授予它訪問權限。這對于 Java 應用程式來說可能很棘手。我不太確定你是如何修復它的(我在我的 mac 上做了一些事情來擺脫它,但我不記得是什么 - 可能開箱即用的 java 應用程式只是閱讀他們想要的任何東西,它只是真正的 mac被偽沙盒化的應用程式。重點是,即使這個東西的 unix 檔案權限表明你應該能夠閱讀它,也有可能是 mac 的應用程式訪問控制拒絕它)。
- 是一個普通的舊檔案,而不是目錄或諸如此類的東西。
Files.move可以(通常 - 取決于 impl 和底層作業系統)通常對目錄進行,但不是Files.copy. 您使用的是編程語言,而不是外殼。如果要復制整個目錄,請撰寫執行此操作的代碼。
uj5u.com熱心網友回復:
不確定我的評論是否被理解,盡管得到了回答。
ìn java SEtarget不能是目標目錄。在檔案復制的其他 API 中,可以說COPY FILE TO DIRECTORY. 在java中不是這樣;這是有意設計來消除一個錯誤原因。
這種風格是:
Path source = Paths.get(sourcePath);
if (Files.isRegularFile(source)) {
Path target = Paths.get(targetPath);
Files.createDirectories(target);
if (Files.isDirectory(target)) {
target = Paths.get(targetPath, source.getFileName().toString());
// Or: target = target.resolve(source.getFileName().toString());
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
更好地確保呼叫時使用完整路徑。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371605.html
標籤:爪哇 例外 java.nio.file
