基本信息
- Hutool 是一个小而全的Java工具类库
- API 文档
https://apidoc.gitee.com/dromara/hutool/
2. 实战
- 一般引用
hutool-core
,如果要用全部hutool-all
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.6.5</version>
</dependency>
2.1 读取文件
- FileUtil.readString(url, CharsetUtil.UTF_8);
- FileUtil.readUtf8String(path);
@Test
public void readFile() {
// resources 目录下
String fileName = "user.json";
String str = FileUtil.readUtf8String(fileName);
JSONObject jsonObj = JSON.parseObject(str);
}
@Test
public void readFile2() {
String fileName = "user.json";
URL url = Thread.currentThread().getContextClassLoader().getResource(fileName);
String str = FileUtil.readUtf8String(url.getPath());
JSONObject jsonObj = JSON.parseObject(str);
}
2.2 写入文件
- 追加模式 FileUtil.appendUtf8String(str, path);
@Test
public void writeFile() {
List<String> values = Arrays.asList("aaa", "bbb", "中文");
String path = "/Users/.../resources/demo.txt";
values.forEach(str -> FileUtil.appendUtf8String(str + "\r\n", path));
}
获取项目目录,并添加文件
@Test
public void writeFile2() {
String fileName = "application.yml";
URL url = Thread.currentThread().getContextClassLoader().getResource(fileName);
String path = url.getPath();
String filePath = path.substring(0, path.indexOf("/target/classes")) + "/files/demo.txt";
List<String> values = Arrays.asList("aaa", "bbb", "中文");
values.forEach(str -> {
FileUtil.appendUtf8String(str, filePath);
FileUtil.appendUtf8String("\r\n", filePath);
});
}
@Test
public void replaceFile() {
String fileName = "user.json";
URL url = Thread.currentThread().getContextClassLoader().getResource(fileName);
String filePath = url.getPath()
.replaceAll("target/classes", "src/main/resources/files")
.replaceAll("\\.json", "\\.txt");
String content = FileUtil.readUtf8String(fileName);
JSONObject jsonObj = JSON.parseObject(content);
// for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
//
// }
// forEach(BiConsumer) --> void accept(T t, U u);
jsonObj.forEach((str, obj) -> {
FileUtil.appendUtf8String(str + ", value=" + obj, filePath);
FileUtil.appendUtf8String("\r\n", filePath);
});
}
网友评论