• java中将文件夹里面的文件复制到指定的文件夹(java IO)


    //现在制定路径下创建名称为左侧的文件夹
    public class Copy {
    
    	public static void main(String[] args) {
    		 //原始文件地址
            File srcFolder = new File("C:\Users\Pei\Desktop\测试复制");
            //原始文件名
            String srcFloderName = srcFolder.getName();
            System.out.println(srcFloderName);
            //要复制到的文件
            File desFolder = new File("C:\Users\Pei\Desktop\左侧", srcFloderName);
            //如果要复制到的文件没有这个文件夹,就创建一个
            if (!desFolder.exists()){
                desFolder.mkdir();
            }
            try {
    			copyFolder(srcFolder,desFolder);
    		} catch (IOException e) {
    			
    			e.printStackTrace();
    		}
    
    	}
    	//复制文件夹
        private static void copyFolder(File srcFolder, File desFolder) throws IOException {
            //遍历原始文件夹里面的所有文件及文件夹
            File[] files = srcFolder.listFiles();
            for (File srcFile : files) {
                //如果是文件夹
                if (srcFile.isDirectory()){
                    //在新的文件夹内创建一个和srcFile文件夹同名文件夹,然后再递归调用,判断文件夹里面的情况,然后做出相应处理
                    String srcFileName = srcFile.getName();
                    File newFolder = new File(desFolder, srcFileName);
                    if (!newFolder.exists()){
                        newFolder.mkdir();
                        copyFolder(srcFile,newFolder);
                    }
                    //如果是文件
                }else {
                    String srcFileName = srcFile.getName();
                    File desFile = new File(desFolder, srcFileName);
                    copyFile(srcFile,desFile);
                }
    
            }
        }
        
        //复制文件(这里复制文件如果看不懂的请看我另一篇博客[IO流详解](https://blog.csdn.net/tannins_/article/details/99298995))
        private static void copyFile (File srcFile, File desFile) throws IOException {
            BufferedReader br = new BufferedReader((new InputStreamReader(new FileInputStream(srcFile),"utf-8")));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(desFile),"utf-8"));
            char[] chars = new char[1024];
            int len;
            while ((len = br.read(chars)) != -1) {
                bw.write(len);
                bw.flush();
            }
            br.close();
            bw.close();
        }
        
    

      

  • 相关阅读:
    Flesch Reading Ease(模拟)
    实验一:词法分析设计
    java—容器学习笔记
    [转载]马士兵Java视频教程 —— 学习顺序
    Java的安装过程
    编程之美初赛第一场
    RCC 2014 Warmup (Div. 2)
    ural 1017. Staircases(dp)
    ural 1012. K-based Numbers. Version 2(大数dp)
    ural 1009. K-based Numbers(简单dp)
  • 原文地址:https://www.cnblogs.com/xianz666/p/13739875.html
Copyright © 2020-2023  润新知