這是我的代碼,我想創建方法,接受檔案并將其移動到我指定檔案夾的電腦中。我只是將現有的文本檔案復制到另一個文本檔案,但我想移動到指定的檔案夾中,而不是復制。如何解決這個問題呢?
public static void main(String[] args) {
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File("C:\\Users\\anar.memmedov\\Desktop\\test.txt");
File bfile = new File("C:\\Users\\anar.memmedov\\Desktop\\ok\\test3.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
}
uj5u.com熱心網友回復:
您可以簡單地使用Files.move:https : //docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path, java.nio.file.路徑, java.nio.file.CopyOption...)
將檔案移動或重命名為目標檔案。默認情況下,此方法嘗試將檔案移動到目標檔案,如果目標檔案存在,則失敗,除非源和目標是同一檔案,在這種情況下,此方法無效。如果檔案是符號鏈接,則移動符號鏈接本身,而不是鏈接的目標。可以呼叫此方法來移動空目錄。在一些實作中,目錄具有在創建目錄時創建的特殊檔案或鏈接的條目。在這樣的實作中,當只有特殊條目存在時,目錄被認為是空的。當呼叫移動非空目錄時,如果不需要移動目錄中的條目,則移動該目錄。例如,重命名同一 FileStore 上的目錄通常不需要移動目錄中的條目。當移動目錄需要移動其條目時,此方法將失敗(通過拋出 IOException)。移動檔案樹可能涉及復制而不是移動目錄,這可以使用 copy 方法和 Files.walkFileTree 實用程式方法來完成。
Path sourcePath = Paths.get("sourceFile.txt");
Path targetPath = Paths.get("targetFolder\\" sourcePath.getFileName());
Files.move(sourcePath, targetPath);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318441.html
