Java.io.File 不包含任何現成讓移動文件的方法,但您可以用以下兩種方式解決辦法:
- File.renameTo().
- 複製到新的文件,並刪除原文件。
在下麵兩個例子,移動一個文件“C:\\folderA\\Afile.txt”從一個目錄到具有相同文件名的另一個目錄“C:\\folderB\\Afile.txt”。
1. File.renameTo()
package com.yiibai.file; import java.io.File; public class MoveFileExample { public static void main(String[] args) { try{ File afile =new File("C:\\folderA\\Afile.txt"); if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){ System.out.println("File is moved successful!"); }else{ System.out.println("File is failed to move!"); } }catch(Exception e){ e.printStackTrace(); } } }
2. 複製和刪除
package com.yiibai.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class MoveFileExample { public static void main(String[] args) { InputStream inStream = null; OutputStream outStream = null; try{ File afile =new File("C:\\folderA\\Afile.txt"); File bfile =new File("C:\\folderB\\Afile.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(); } } }