Java去除掉文件夹中所有.java文件的注释和空行并输出到指定文件中

只需按照自己的需求修改 input和output的路径即可

import java.io.*;

public class SoftFileTest {
    public static void main(String[] args) throws IOException {
        File input = new File("D:\\项目开发\\实验室项目");
        File output = new File("D:\\code.txt");
        if(!output.exists()){
            output.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(output));

        StringBuffer sb = new StringBuffer();
        loopRead(input,sb);
        write(sb.toString(),bw);
    }

    private static String readFileToString(File file) {
        BufferedReader bf = null;
        StringBuilder sb = new StringBuilder();
        try {
            bf = new BufferedReader(new FileReader(file));
            String line;
            while ((line = bf.readLine()) != null) {
                String s = line.trim();
                if (s.length() == 0) {
                    continue;
                }
                if (s.startsWith("/") || s.startsWith("*")) {
                    continue;
                }
                sb.append(line);
                sb.append("\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bf != null) {
                    bf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    private static void loopRead(File dir, StringBuffer sb) {
        File[] files = dir.listFiles();
        if (files != null) {
            for(File file:files){
                if(file.isDirectory()){
                    loopRead(file,sb);
                }
                else if (file.length()!=0&&file.isFile()&&file.getName().endsWith(".java")){
                    sb.append(readFileToString(file));
                }
            }
        }
    }

    private static void write(String str,BufferedWriter bw){
        try {
            bw.write(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try{
                if(bw!=null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值