学以致用——Java批量更改文件字符编码

代码

参考:疯狂Java讲义(第五版)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
public static void main(String[] args) throws IOException {
// 我的文件夹位置
String codes = "C:/Users/dcsuibian/study/疯狂Java讲义/codes";
Files.walk(Path.of(codes))
// 过滤掉所有非 .java 文件
.filter(path -> path.toString().endsWith(".java"))
.forEach(path -> {
try {
String s = Files.readString(path, Charset.forName("GBK"));
Files.writeString(path, s, Charset.forName("UTF-8"));
} catch (IOException e) {
System.out.println("出错的文件:" + path);
e.printStackTrace();
}
});
}
}

效果

运行前:

image-20210501195024201

image-20210501195059993


运行后:

image-20210501195133387

成功!!!