zoukankan      html  css  js  c++  java
  • 文件拷贝案例

    用到的知识点有:FileInputStream、FileOutputStream、File对象的常用方法、重点是递归方法路径的拼接

    package com.yc.day0829;
    
    import java.io.*;
    
    /**
     * @program: javaSE
     * 描述:
     * 将D:\aa文件全部copy到c盘中
     * @author: yc
     * @create: 2020-08-29 15:28
     **/
    public class CopyTest {
        public static void main(String[] args) {
    //拷贝源和拷贝目标的路径都是可能改变的。 File srcFile
    = new File("D:\aa"); //拷贝源 File destFile = new File("c:\"); //拷贝目标 copyDir(srcFile,destFile); //调用方法拷贝 } private static void copyDir(File srcFile, File destFile) { if(srcFile.isFile()){ //源File对象是文件的话,就将文件进行I/o读写操作。 FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(srcFile); //这里使用endwith()方法是因为路径尾部有可能没有带“”,可能程序会出错。 String path = (destFile.getAbsolutePath().endsWith("\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\") +srcFile.getAbsolutePath().substring(3); //这里的3是根据你的拷贝源的需求来截取的。path是拷贝目标下文件的路径。 fos = new FileOutputStream(path); //创建fos对象的同时也会在指定路径的硬盘上生成文件。初学者疑惑的地方 byte[] bytes = new byte[1024*1024]; int c = 0; while((c = fis.read(bytes))!= -1){ fos.write(bytes,0,c); } fos.flush(); //刷新 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } return; //如果是一个文件的话,递归结束 } //获取源下面的子目录 File[] files = srcFile.listFiles(); for (File file : files) { if(file.isDirectory()){ //新建对应的目录 String srcDir = file.getAbsolutePath(); String destDir = (destFile.getAbsolutePath().endsWith("\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\") +srcDir.substring(3); //destDir是拷贝目标下的文件夹的路径。 File newFile = new File(destDir); if(!newFile.exists()){ //File对象如果不存在,就创建多级文件夹。 newFile.mkdirs(); } } //递归 copyDir(file,destFile); //重点理解。 } } }
  • 相关阅读:
    commons-dbutils实现增删改查(spring新注解)
    commons-dbutils实现增删改查
    配置扫描注解的包
    常用注解
    注入集合类型数据
    spring创建bean的三种方式
    switch
    jvm编译器的优化
    java9小工具jshell
    java三元运算符
  • 原文地址:https://www.cnblogs.com/yclss123/p/13582913.html
Copyright © 2011-2022 走看看