整理文档,搜刮出一个Java实现文件或文件夹的复制到指定目录的代码,稍微整理精简一下做下分享。
进口java.io.File; 进口java.io.FileInputStream; 进口java.io.FileOutputStream; 公共类测试{ 私有静态int=5; 公共静态void main (String [] args) {//需要复制的目标文件或目标文件夹 路径名字符串=" C:/用户/likun/桌面/git_project”; 文件文件=新文件(路径);//复制到的位置 字符串topathname=" C:/用户/likun/桌面/电影”; 文件去整理=新文件(topathname); 尝试{ 复制(文件,去整理); }捕捉(异常e) {//TODO自动生成的catch块 e.printStackTrace (); } } 公共静态空副本(文件文件,文件去整理){抛出异常 byte [] b=新的字节[1024]; int; FileInputStream fis; FileOutputStream安全系数; 如果(file.isDirectory ()) { 字符串filepath=file.getAbsolutePath (); filepath=filepath。replaceAll ("\\\", "/"); 字符串toFilepath=toFile.getAbsolutePath (); toFilepath=toFilepath。replaceAll ("\\\", "/"); int lastIndexOf=filepath.lastIndexOf (“/?; toFilepath=toFilepath + filepath。substring (lastIndexOf filepath.length ()); 文件复制=新文件(toFilepath);//复制文件夹 如果(! copy.exists ()) { copy.mkdir (); }//遍历文件夹 (文件f: file.listFiles ()) { 复制(f,复制); } 其他}{ 如果(toFile.isDirectory ()) { 字符串filepath=file.getAbsolutePath (); filepath=filepath。replaceAll ("\\\", "/"); 字符串toFilepath=toFile.getAbsolutePath (); toFilepath=toFilepath。replaceAll ("\\\", "/"); int lastIndexOf=filepath.lastIndexOf (“/?; toFilepath=toFilepath + filepath。substring (lastIndexOf filepath.length ());//写文件 文件newFile中=新文件(toFilepath); fis=new FileInputStream(文件); 安全系数=new FileOutputStream (newFile中); 在((=fis.read (b)) !=1) { 安全系数。写(0,b); } 其他}{//写文件 fis=new FileInputStream(文件); 安全系数=new FileOutputStream(去整理); 在((=fis.read (b)) !=1) { 安全系数。写(0,b); } } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。