编程实现将d盘根目录下存在的图片文件a.bmp拷贝到e盘根目录下,文件名重新命名为为b.bmp
1条回答 默认 最新
关注import java.io.*; import java.io.File; public class CopyAll { public static void main(String[] args) { //拷贝源 File srcFile=new File("D:\\a.bmp"); //拷贝目标 File destFile=new File("E:\\b.bmp"); //调用拷贝的方法 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];//一次复制1Mb int 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);//递归 } } }解决 无用评论 打赏 举报 编辑记录