在《 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);
}
}