簡體   English   中英

用Java復制文件

[英]Copying files with Java

我嘗試在替換舊文件時將文件從一個位置復制到另一個位置,但不斷出現此錯誤: The method copy(Path, Path, CopyOption...) in the type Files is not applicable for the arguments (File, File, StandardCopyOption)

我的代碼如下

Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);

我也嘗試過使用這種方法:

CopyOption[] options = new CopyOption[]{
  StandardCopyOption.REPLACE_EXISTING
}; 
Files.copy(file1, file2, options[0]);

我得到這個錯誤: The method copy(Path, Path, CopyOption...) in the type Files is not applicable for the arguments (File, File, CopyOption)

有什么想法嗎?

您需要傳遞Path對象,而不是File

Files.copy(file1.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);

從有用的錯誤消息來看, file1file2File對象。

但是您需要將Path對象傳遞給copy方法。

所以你需要使用

Files.copy(file1.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);

代替。

您不應該使用文件。 而不是使用路徑。

Files.copy(file1.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);

您是否嘗試過投放StandardCopyOption?

嘗試:

    CopyOption co = (CopyOption) StandardCopyOption.REPLACE_EXISTING;

基於您收到的錯誤,在我看來,即使方法Files.copy()使用Inputstream或Path,而不是Files,您也​​在使用文件。

這可能是Java復制文件的副本, 並替換了現有目標

希望這可以幫助。 祝你好運:)

暫無
暫無

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

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