0
点赞
收藏
分享

微信扫一扫

利用JAVA程序将所有JAVA文件内容添加到一个文件中(代码加注释详解)

荷一居茶生活 2022-01-20 阅读 37
package A1;

import java.io.*;

/**
 * @author yeqv
 * @program A2
 * @Classname a4
 * @Date 2022/1/18 17:06
 * @Email w16638771062@163.com
 */
public class a4 {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("D:\\idea\\ja");
        thow(file);


    }

    public static void thow(File file) {
        //判断文件名是否为目录
        if (file.isDirectory()) {
            //转为FILE类型数组
            File[] files = file.listFiles();
            //遍历子目录
            for (File file1 : files) {
                //判断是否为子目录,如果是就递归
                if (file1.isDirectory()) {
                    thow(file1);
                }
                //判断子目录是否是普通文件,并且后缀是java
                if (file1.isFile() && file1.getName().endsWith(".java")) {
                    //new一个输入流对象和输出流对象,并创建一个文件
                    try (var a = new FileOutputStream("D:\\java123.java", true); var b = new FileInputStream(file1.getAbsolutePath())) {
              //将对象b的内容添加到文件a中
                        b.transferTo(a);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

        }
        //判断文件是否是普通文件,并且后缀是java
        if (file.isFile() && file.getName().endsWith(".java")) {
            //new一个输入流对象和输出流对象,并创建一个文件
            try (var a = new FileOutputStream("D:\\java123.java", true); var b = new FileInputStream(file.getAbsolutePath())) {
                //将对象b的内容添加到文件a中
                b.transferTo(a);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}

举报

相关推荐

0 条评论