100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > java文件的拷贝/复制

java文件的拷贝/复制

时间:2024-01-08 07:18:15

相关推荐

java文件的拷贝/复制

用java完成两个文件之间可拷贝

先对源文件的目录进行遍历新建,接着目标对文件指定的相对路径下进行创建,以此完成拷贝

代码实现:

package iO;import java.io.*;import java.io.File;public class CopyAll {public static void main(String[] args) {//拷贝源File srcFile=new File("D:\\LC\\新建文件夹");//拷贝目标File destFile=new File("C:\\");//调用拷贝的方法copys(srcFile,destFile);}/*拷贝方法*/private static void copys(File srcFile, File destFile) {//如果当前的是文件的话if(srcFile.isFile()){/*是文件的时候需要拷贝* 边读边写*/FileInputStream in=null;FileOutputStream out=null;try {in=new FileInputStream(srcFile);//读取/*目标目录文件+源盘符后的文件路径* 三目运算符:如果文件路径结尾没有有"\\"则加上*/String sof=(destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\")+srcFile.getAbsolutePath().substring(3);out=new FileOutputStream(sof);//写出byte[] bytes=new byte[1024*1024];//一次复制1Mbint count=0;while ((count=in.read(bytes))!=-1){out.write(bytes,0,count);}out.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(in!=null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(out!=null){try {out.close();} catch (IOException e) {e.printStackTrace();}}}return;}//获取源文件的子目录File[] files=srcFile.listFiles();for(File file:files){//如果file是一个目录的话if(file.isDirectory()){//新建对应目录String srcDir=file.getAbsolutePath();//源目录绝对路径//目标目录当前的绝对路径+源目录的目录路径,srcDir.substring(3)将源文件的盘符分割String desDir=(destFile.getAbsolutePath().endsWith("\\")? destFile.getAbsolutePath() : destFile.getAbsolutePath()+"\\")+srcDir.substring(3);File newFile=new File(desDir);//将目标目录路径新建//如果对对象不存在if(!newFile.exists()){newFile.mkdirs();//新建目录}}/*递归当前获取到的文件*/copys(file,destFile);//递归}}}

再main方法中输入目标相对应的绝对路径即可进行文件的拷贝

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。