Java实现文件或文件夹的复制到指定目录实例
程序员文章站
2024-03-02 16:17:52
整理文档,搜刮出一个java实现文件或文件夹的复制到指定目录的代码,稍微整理精简一下做下分享。
import java.io.file;
import j...
整理文档,搜刮出一个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); } } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。