1. 程式人生 > >java 檔案移動,複製

java 檔案移動,複製

public static boolean copyFromSourceToDestFile(File sourceFile, //原路徑
  File destFile,//目標路徑
  boolean move )//true 為 移動 false為複製
      throws IOException {
createPath(destFile, true);
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
if (move) {
sourceFile.delete();
}
return true;
}
public static void createPath(File file, boolean asFile) throws IOException {
String path = file.getAbsolutePath();
String dirPath;
if (asFile) {
dirPath = path.substring(0, path.lastIndexOf(File.separator));
} else {
dirPath = path;
}


File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
if (asFile) {
file.createNewFile();
}

}

我是從ckfinder原始碼里弄出來的