簡體   English   中英

將所有文件從源文件復制到目標 Java

[英]Copy all files from Source to Destination Java

我必須編寫一個 java 方法 public void public void copyTo(Path rSource, Path rDest) 將所有文件從現有目錄 rSource 復制到具有相同名稱的新目錄 rDest。 rSource 必須存在且 rDest 必須不存在,如果不為 true,則運行時異常。 我似乎無法讓它工作,幫助!

我試過的:

public void copyTo(Path rSource, Path rDest){
    if(!(Files.exists(rSource) && Files.isDirectory(rSource)) || (Files.exists(rDest))){
        throw new RuntimeException();
    }
    try {
        Files.createDirectory(rDest);
        if(Files.exists(rDest)){
            try(DirectoryStream<Path> stream = Files.newDirectoryStream(rSource)) {
                for(Path p : stream) {
                    System.out.println(p.toString());
                    Files.copy(p, rDest);
                }
            } catch( IOException ex) {
            }
        }
    } catch (IOException e) {
    }
}

Files.copy() 至少需要兩個參數,源和目標文件路徑或流。 您的情況的問題是您正在傳遞 rDest 文件夾路徑,而不是實際的文件路徑。 只需修改 for 循環中的代碼,將文件名從源附加到目標文件夾路徑:

Path newFile = Paths.get(rDest.toString() + "/" + p.getFileName());
Files.copy(p, newFile);

如果我錯了糾正我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM