读文件小工具

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ReadFile {
	
	private static List<String> filePath = new ArrayList<String>();
	
	public static void main(String[] args) {
		String str = "";
		traverseFolder2("D:\\work\\aimMaster");
		for(int i=0;i<filePath.size();i++) {
			System.out.println(filePath.get(i));
			try {
				str += readFile(new File(filePath.get(i)));
			} catch (IOException e) {
				e.printStackTrace();
			}
			BufferedWriter out;
			try {
				out = new BufferedWriter(new FileWriter("d:\\code.txt"));
		        out.write(str);
		        out.flush();
		        out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
	
	public static List<String> traverseFolder2(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null == files || files.length == 0) {
//                System.out.println("文件夹是空的!");
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
//                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        traverseFolder2(file2.getAbsolutePath());
                    } else {
                    	String path2 = file2.getAbsolutePath();
                    	if(path2.endsWith(".java")) {
                    		filePath.add(path2);
//                    		System.out.println(path2);
                    	}                       
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        return filePath;
    }
	

	public static String readFile(File path) throws IOException{
		InputStream is = new FileInputStream(path);
		byte[] bytes = new byte[is.available()];
		int len = is.read(bytes);
		String str = null;
		while(len!=-1){
			str = new String(bytes, 0, len);
			len = is.read(bytes);
		}
		is.close();
		return str;
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值