美文网首页
Java实现复制并修改部分文件后缀名

Java实现复制并修改部分文件后缀名

作者: ShenHehe | 来源:发表于2018-03-08 09:13 被阅读0次
    
    public class Test {
    
        public static String DIR = "e:\\Test\\java";//需要复制的源文件地址
    
        public static String DESTDIR = "e:\\Test\\aaa";//拷贝后存放的地址
    
        public static void main(String[] args) throws Exception { 
    
        System.out.println("开始");
    
        traverseFolder(DIR);
    
        System.out.println("结束");
    
        } 
    
    
        public static void copy(InputStream in, OutputStream out) throws Exception { 
    
            byte[] buf = new byte[1024]; 
    
            int len = 0; 
    
            /*读取文件内容并写入文件字节流中*/ 
    
            while((len = in.read(buf))!=-1) { 
    
                out.write(buf, 0, len); 
    
            } 
    
        } 
    
    
        public static void traverseFolder(String path) throws Exception {
    
        File file = new File(path);
    
            if (file.exists()) {
    
                File[] files = file.listFiles();
    
                if (files.length == 0) {
    
                    System.out.println(file.getAbsolutePath() + " 空文件夹!");
    
                    return;
    
                } else {
    
                    for (File file2 : files) {
    
                        if (file2.isDirectory()) {
    
                        //如果是文件夹创建文件夹
    
                        File str = new File(file2.getAbsolutePath().toString().replace(DIR, DESTDIR));
    
                        str.mkdir();
    
                        //递归查找该文件夹里面的文件                   
    
                            traverseFolder(file2.getAbsolutePath());
    
                        }else {
    
                        FileInputStream fis = new FileInputStream(file2); 
    
                        //修改后缀名(java改txt)
    
                        String destFileName = file2.getName().replaceAll("\\.java$", "\\.txt"); 
    
                        FileOutputStream fos = new FileOutputStream(new File(file2.getParent().toString().replace(DIR, DESTDIR), destFileName)); 
    
                        //复制写入
    
                        copy(fis, fos); 
    
                        fis.close(); 
    
                        fos.close();
    
                        }
    
                    }
    
                }
    
            } else {
    
                System.out.println("文件不存在!");
    
            }
    
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:Java实现复制并修改部分文件后缀名

          本文链接:https://www.haomeiwen.com/subject/uiuefftx.html