java文件编码转换器_【转载】Java文件编码自动转换工具类

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 public class ChangeFileEncoding {

2 public static int fileCount = 0;

3 public static String sourceFileRoot = "替换为要转换的源文件或源目录"; // 将要转换文件所在的根目录

4 public static String sourceCharset = "GB2312"; // 源文件编码

5 public static String targetCharset = "utf8"; // 目标文件编码

6 public static void main(String[] args) throws IOException {

7 File fileDir = new File(sourceFileRoot);

8 convert(fileDir);

9 System.out.println("Total Dealed : " + fileCount + "Files");

10 }

11

12 public static void convert(File file) throws IOException {

13 // 如果是文件则进行编码转换,写入覆盖原文件

14 if (file.isFile()) {

15 // 只处理.java结尾的代码文件

16 if (file.getPath().indexOf(".java") == -1) {

17 return;

18 }

19 InputStreamReader isr = new InputStreamReader(new FileInputStream(

20 file), sourceCharset);

21 BufferedReader br = new BufferedReader(isr);

22 StringBuffer sb = new StringBuffer();

23 String line = null;

24 while ((line = br.readLine()) != null) {

25 // 注意写入换行符

26 line = URLEncoder.encode(line, "utf8");

27 sb.append(line + "\r\n");//windows 平台下 换行符为 \r\n

28 }

29 br.close();

30 isr.close();

31

32 File targetFile = new File(file.getPath());

33 OutputStreamWriter osw = new OutputStreamWriter(

34 new FileOutputStream(targetFile), targetCharset);

35 BufferedWriter bw = new BufferedWriter(osw);

36 // 以字符串的形式一次性写入

37 bw.write(URLDecoder.decode(sb.toString(), "utf8"));

38 bw.close();

39 osw.close();

40

41 System.out.println("Deal:" + file.getPath());

42 fileCount++;

43 } else {

44 //利用递归对目录下的每个以.java结尾的文件进行编码转换

45 for (File subFile : file.listFiles()) {

46 convert(subFile);

47 }

48 }

49 }

50

51 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值