Java读写文件

1. 知道文件确定路径

如果是读取xml文件,可以读取inputStream,再用XMLConfiguration处理

import java.io.InputStream;
import org.apache.commons.configuration.XMLConfiguration;


// 由path获取inputStream
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);

// 由inputStream创建xml处理器
XMLConfiguration xmlConfiguration = new XMLConfiguration();
xmlConfiguration.load(in);

或则使用InputStreamReader逐行处理

// 读
InputStreamReader inReader = new InputStreamReader(new FileInputStream(path), "UTF8");

BufferedReader buReader = new BufferedReader(inReader);

try {
    String fromLine = null;
    while ((fromLine = buReader.readLine()) != null) {
        // 使用formLine
    }

} finally{
    buReader.close();
    inReader.close();
}



// 写
OutputStreamWriter outWriter = new OutputStreamWriter(new FileOutputStream(path),
                "UTF8");

BufferedWriter buWriter = new BufferedWriter(outWriter);
            
String toLine = "something to write";

try {
    buWriter.write(toLine);

} finally {
    buWriter.close();
    outWriter.close();
}

2. 不知道文件确定路径,需要扫描

Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(dirPath);

recursive = true;

if (dirs.hasMoreElements()) {
    URL url = dirs.nextElement();
    String protocol = url.getProtocol();

    if ("file".equals(protocol)) {
        String filePath = URLDecoder.decode(url.getFile(), "UTF-8");

        File dir = new File(filePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }

        File[] subDirs = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });

         if (subDirs == null || subDirs.length == 0) {
            return;
        }

         for (File f : subDirs) {
            if (f.isDirectory()) {
                // 递归处理文件夹
                continue;
            }

            className = f.getName();
            className = packageName + "." + className.substring(0, className.length() - 6);

            // 处理文件
            Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        }
    }
}

或则递归访问所有文件及子文件

handle(File file) {
    if (file.isFile) {
        // 只处理.java结尾的代码文件
        if (!file.getPath().endsWith(".java")) {
            return;
        }

        // 处理逻辑

    } else {
        File[] files = file.listFiles();
        if (files == null) {
            return;
        }
        for (File subFile : files) {
            handle(subFile);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值