批量把文件编码由GBK转UTF-8

这是一个Java程序,用于批量将指定目录下的GBK编码文件转换为UTF-8编码。程序通过递归遍历目录,读取GBK编码的文件内容,然后将其转换为UTF-8并保存到新的目录中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java代码  收藏代码
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStreamWriter;  
  10. import java.io.UnsupportedEncodingException;  
  11. import java.text.MessageFormat;  
  12.   
  13. /** 
  14.  * 批量把文件编码由GBK转为UTF8,可以继续完善做成在命令行中执行的程序, 可以添加文件名过滤等功能,暂时未实现。 
  15.  *  
  16.  */  
  17. public class FileGBK2UTF8 {  
  18.   
  19.     public static void main(String[] args) {  
  20.         // 需要转换的文件目录  
  21.         String fromPath = "D:\\input";  
  22.         // 转换到指定的文件目录  
  23.         String toPath = "D:\\output";  
  24.   
  25.         info("start transform [from path]={0} [to path]={1}", fromPath, toPath);  
  26.   
  27.         // 递归取到所有的文件进行转换  
  28.         transform(fromPath, toPath);  
  29.     }  
  30.   
  31.     /** 
  32.      * 把一个目录中的文件转换到另一个目录中 
  33.      *  
  34.      * @param fromPath 
  35.      *            -- 来源文件目录 
  36.      * @param toPath 
  37.      *            -- 目标文件目录 
  38.      * @return 
  39.      */  
  40.     public static boolean transform(String fromPath, String toPath) {  
  41.         File ftmp = new File(fromPath);  
  42.         if (!ftmp.exists()) {  
  43.             info("转换文件路径错误!");  
  44.             return false;  
  45.         }  
  46.   
  47.         info("frompath is [{0}], topath is [{1}]", fromPath, toPath);  
  48.   
  49.         // 如果是文件,则转换,结束  
  50.         if (ftmp.isFile()) {  
  51.             byte[] value = fileToBytes(fromPath);  
  52.             String content = convEncoding(value, "gbk""utf-8");  
  53.             return saveFileUtf8(toPath, content);  
  54.         } else {  
  55.             // 查找目录下面的所有文件与文件夹  
  56.             File[] childFiles = ftmp.listFiles();  
  57.             for (int i = 0, n = childFiles.length; i < n; i++) {  
  58.                 File child = childFiles[i];  
  59.                 String childFrom = fromPath + "/" + child.getName();  
  60.                 String childTo = toPath + "/" + child.getName();  
  61.   
  62.                 transform(childFrom, childTo);  
  63.             }  
  64.         }  
  65.   
  66.         return true;  
  67.     }  
  68.   
  69.     /** 
  70.      * 把文件内容保存到指定的文件中,如果指定的文件已存在,则先删除这个文件, 如果没有则创建一个新文件,文件内容采用UTF-8编码方式保存。 
  71.      * 如果指定的文件路径不存在,则先创建文件路径,文件路径从根目录开始创建。 
  72.      *  
  73.      * @param fileName 
  74.      *            -- 文件路径 
  75.      * @param content 
  76.      *            -- 文件内容 
  77.      * @return 
  78.      */  
  79.     public static boolean saveFileUtf8(String fileName, String content) {  
  80.         if (fileName == null || fileName.length() == 0)  
  81.             return false;  
  82.         if (content == null)  
  83.             return false;  
  84.   
  85.         // 路径中的\转换为/  
  86.         fileName = fileName.replace('\\', '/');  
  87.         // 处理文件路径  
  88.         createPath(fileName.substring(0, fileName.lastIndexOf('/')));  
  89.   
  90.         File file = null;  
  91.         FileOutputStream out = null;  
  92.         try {  
  93.             // 创建或修改文件  
  94.             file = new File(fileName);  
  95.   
  96.             if (file.exists()) {  
  97.                 file.delete();  
  98.             } else {  
  99.                 file.createNewFile();  
  100.             }  
  101.   
  102.             out = new FileOutputStream(file);  
  103.             // 添加三个字节标识为UTF-8格式,也是BOM码  
  104.             // out.write(new byte[]{(byte)0xEF,(byte)0xBB,(byte)0xBF});  
  105.             out.write(content.getBytes("UTF-8"));  
  106.         } catch (FileNotFoundException e) {  
  107.             e.printStackTrace();  
  108.             return false;  
  109.         } catch (IOException e) {  
  110.             e.printStackTrace();  
  111.             return false;  
  112.         } finally {  
  113.             if (out != null) {  
  114.                 try {  
  115.                     out.flush();  
  116.                     out.close();  
  117.                 } catch (IOException e) {  
  118.                     e.printStackTrace();  
  119.                     return false;  
  120.                 }  
  121.             }  
  122.         }  
  123.   
  124.         return true;  
  125.     }  
  126.   
  127.     /** 
  128.      * 把文件内容转换为字节数组输出。 
  129.      *  
  130.      * @param fileName 
  131.      *            -- 文件名 
  132.      * @return 
  133.      */  
  134.     public static byte[] fileToBytes(String fileName) {  
  135.         FileInputStream ins = null;  
  136.         ByteArrayOutputStream bos = null;  
  137.         try {  
  138.             // 创建文件读入流  
  139.             ins = new FileInputStream(new File(fileName));  
  140.             // 创建目标输出流  
  141.             bos = new ByteArrayOutputStream();  
  142.   
  143.             // 取流中的数据  
  144.             int len = 0;  
  145.             byte[] buf = new byte[256];  
  146.             while ((len = ins.read(buf, 0256)) > -1) {  
  147.                 bos.write(buf, 0, len);  
  148.             }  
  149.   
  150.             // 目标流转为字节数组返回到前台  
  151.             return bos.toByteArray();  
  152.         } catch (Exception e) {  
  153.             e.printStackTrace();  
  154.         } finally {  
  155.             try {  
  156.                 if (ins != null) {  
  157.                     ins.close();  
  158.                     ins = null;  
  159.                 }  
  160.                 if (bos != null) {  
  161.                     bos.close();  
  162.                     bos = null;  
  163.                 }  
  164.             } catch (Exception e) {  
  165.                 e.printStackTrace();  
  166.             }  
  167.         }  
  168.   
  169.         return null;  
  170.     }  
  171.   
  172.     /** 
  173.      * 检查指定的文件路径,如果文件路径不存在,则创建新的路径, 文件路径从根目录开始创建。 
  174.      *  
  175.      * @param filePath 
  176.      * @return 
  177.      */  
  178.     public static boolean createPath(String filePath) {  
  179.         if (filePath == null || filePath.length() == 0)  
  180.             return false;  
  181.   
  182.         // 路径中的\转换为/  
  183.         filePath = filePath.replace('\\', '/');  
  184.         // 处理文件路径  
  185.         String[] paths = filePath.split("/");  
  186.   
  187.         // 处理文件名中没有的路径  
  188.         StringBuilder sbpath = new StringBuilder();  
  189.         for (int i = 0, n = paths.length; i < n; i++) {  
  190.             sbpath.append(paths[i]);  
  191.             // 检查文件路径如果没有则创建  
  192.             File ftmp = new File(sbpath.toString());  
  193.             if (!ftmp.exists()) {  
  194.                 ftmp.mkdir();  
  195.             }  
  196.   
  197.             sbpath.append("/");  
  198.         }  
  199.   
  200.         return true;  
  201.     }  
  202.   
  203.     /** 
  204.      * 取路径中的文件名 
  205.      *  
  206.      * @param path 
  207.      *            -- 文件路径,含文件名 
  208.      * @return 
  209.      */  
  210.     public static String getFileName(String path) {  
  211.         if (path == null || path.length() == 0)  
  212.             return "";  
  213.   
  214.         path = path.replaceAll("\\\\", "/");  
  215.         int last = path.lastIndexOf("/");  
  216.   
  217.         if (last >= 0) {  
  218.             return path.substring(last + 1);  
  219.         } else {  
  220.             return path;  
  221.         }  
  222.     }  
  223.   
  224.     /** 
  225.      * 字符串的编码格式转换 
  226.      *  
  227.      * @param value 
  228.      *            -- 要转换的字符串 
  229.      * @param oldCharset 
  230.      *            -- 原编码格式 
  231.      * @param newCharset 
  232.      *            -- 新编码格式 
  233.      * @return 
  234.      */  
  235.     public static String convEncoding(byte[] value, String oldCharset,  
  236.             String newCharset) {  
  237.         OutputStreamWriter outWriter = null;  
  238.         ByteArrayInputStream byteIns = null;  
  239.         ByteArrayOutputStream byteOuts = new ByteArrayOutputStream();  
  240.         InputStreamReader inReader = null;  
  241.   
  242.         char cbuf[] = new char[1024];  
  243.         int retVal = 0;  
  244.         try {  
  245.             byteIns = new ByteArrayInputStream(value);  
  246.             inReader = new InputStreamReader(byteIns, oldCharset);  
  247.             outWriter = new OutputStreamWriter(byteOuts, newCharset);  
  248.             while ((retVal = inReader.read(cbuf)) != -1) {  
  249.                 outWriter.write(cbuf, 0, retVal);  
  250.             }  
  251.         } catch (Exception e) {  
  252.             e.printStackTrace();  
  253.         } finally {  
  254.             try {  
  255.                 if (inReader != null)  
  256.                     inReader.close();  
  257.                 if (outWriter != null)  
  258.                     outWriter.close();  
  259.             } catch (Exception e) {  
  260.                 e.printStackTrace();  
  261.             }  
  262.         }  
  263.   
  264.         String temp = null;  
  265.         try {  
  266.             temp = new String(byteOuts.toByteArray(), newCharset);  
  267.         } catch (UnsupportedEncodingException e) {  
  268.             e.printStackTrace();  
  269.         }  
  270.         // System.out.println("temp" + temp);  
  271.         return temp;  
  272.     }  
  273.   
  274.     /** 
  275.      * 显示提示信息 
  276.      *  
  277.      * @param message 
  278.      *            -- 信息内容 
  279.      * @param params 
  280.      *            -- 参数 
  281.      */  
  282.     private static void info(String message, Object... params) {  
  283.         message = MessageFormat.format(message, params);  
  284.   
  285.         System.out.println(message);  
  286.     }  
  287. }  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值