[Java]-当前目录下文件读写


在《 spring读取配置文件以及忽略部分文件处理》中介绍了配置文件中操作;在《 Java输入输出流与文件操作简介》中介绍了常用文件流操作;本节就介绍如何获取当前目录并读写文件。

目录获取

通过保护域,可以方便地获取Java程序运行的当前目录。

保护域ProtectionDomain

保护域是用来容纳class文件的,会包含permission与codeSource对象。类装载器将类型装入Java虚拟机时,会为每个类型指派一个保护域。装载入Java虚拟机的每个类型都属于且仅属于一个保护域。
在这里插入图片描述

codeSource扩展了代码库的概念,不仅封装了类的位置(URL),还封装了对应的签名代码的证书链。 类装载器在加载时,会创建一个codeSource对象。

获取路径

通过codeSource中的Location即可获取当前路径:当以jar包方式运行时,路径是jar包中的classes位置;当从编译器中运行时,路径是class所在路径。

public String getCurrentPath() {
    String path = FReadWrite.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    if (path.contains(".jar")) {  // file://E:/.../SpringStudy.jar!/BOOT-INF/classes!/
        path = path.substring(0, path.lastIndexOf("."));
        path = path.substring("file:".length(), path.lastIndexOf("/"));
    } else {
        path = path.replace("/target/classes/", "");
    }
    return path;
}

文件读写

以读取本地文本文件为例,内容为‘字符串+$+数字’条目,每个条目占一行。

读取

通过缓存读取器BufferedReader可以方便地按行读取:

public Map<String, Integer> readResultFile(String strFile) {
    File file = new File(strFile);
    Map<String, Integer> mapResult = new HashMap<>();
    try (final Reader reader = new FileReader(file);
         final BufferedReader bufferedReader = new BufferedReader(reader)) {
        String lines = null;
        final Splitter splitLine = Splitter.on("$").trimResults().limit(2);
        while ((lines = bufferedReader.readLine()) != null) {
            List<String> lst = splitLine.splitToList(lines);
            String name = lst.get(0);
            Integer age = Integer.valueOf(lst.get(1));
            mapResult.put(name, age);
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return mapResult;
}

写入

通过PrintWrite可方便地按行写入:

public void writeResultFile(String strFile, Map<String, Integer> mapResult) {
    File file = new File(strFile);
    if (file.exists() && !file.isDirectory()) {
        System.out.println("Error: it is not a file");
        return;
    }

    try (final FileWriter writer = new FileWriter(file);
         final PrintWriter printWriter = new PrintWriter(writer);) {
        mapResult.forEach((k, v) -> {
            printWriter.printf("%s$%d\n", k, v);
        });
        printWriter.flush();
    } catch (Exception ex) {
        System.out.println(ex);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值