zoukankan      html  css  js  c++  java
  • 【转载】Java文件编码自动转换工具类

     本篇随笔主要介绍了一个用java语言写的将一个文件编码转换为另一个编码并不改变文件内容的工具类:

        通过读取源文件内容,用URLEncoding重新编码解码的方式实现。

          

    复制代码
     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 + "
    ");//windows 平台下 换行符为 
    
    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 }
  • 相关阅读:
    轻松自动化---selenium-webdriver(python) (八)
    轻松自动化---selenium-webdriver(python) (七)
    轻松自动化---selenium-webdriver(python) (六)
    轻松自动化---selenium-webdriver(python) (五)
    轻松自动化---selenium-webdriver(python) (四)
    轻松自动化---selenium-webdriver(python) (三)
    轻松自动化---selenium-webdriver(python) (二)
    轻松自动化---selenium-webdriver(python) (一)
    容器在 Weave 中如何通信和隔离?- 每天5分钟玩转 Docker 容器技术(65)
    Weave 网络结构分析
  • 原文地址:https://www.cnblogs.com/ChoviWu/p/ChoviWu.html
Copyright © 2011-2022 走看看