整理文檔,搜刮出一個Java實現文件或文件夾的復制到指定目錄的代碼,稍微整理精簡一下做下分享。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Test {
private static int a = 5;
public static void main(String[] args) {
//需要復制的目標文件或目標文件夾
String pathname = "C:/Users/likun/Desktop/git_project";
File file = new File(pathname);
//復制到的位置
String topathname = "C:/Users/likun/Desktop/movie";
File toFile = new File(topathname);
try {
copy(file, toFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void copy(File file, File toFile) throws Exception {
byte[] b = new byte[1024];
int a;
FileInputStream fis;
FileOutputStream fos;
if (file.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath=filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath=toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());
File copy=new File(toFilepath);
//復制文件夾
if (!copy.exists()) {
copy.mkdir();
}
//遍歷文件夾
for (File f : file.listFiles()) {
copy(f, copy);
}
} else {
if (toFile.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath=filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath=toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf ,filepath.length());
//寫文件
File newFile = new File(toFilepath);
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
} else {
//寫文件
fis = new FileInputStream(file);
fos = new FileOutputStream(toFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
}
}
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。