编码批量转换

来源:互联网 发布:mac 文件修改器.save 编辑:程序博客网 时间:2024/06/16 09:37
 

package com.demo;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class CharsetConver {
 public static void main(String[] args) throws IOException {
  read("E:\\cms_work\\wjzm\\", "UTF-8");
 }

 private static final String[] extentions = { "java", "js", "html", "htm", "jsp" };

 public static void read(String filepath, String charset) throws IOException {
  File f = new File(filepath);// 定义文件路径
  String path;
  if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
   if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
    return;
   } else {// 若有则把文件放进数组,并判断是否有下级目录
    File delFile[] = f.listFiles();
    int i = f.listFiles().length;
    for (int j = 0; j < i; j++) {
     path = delFile[j].getAbsolutePath();
     if (delFile[j].isDirectory()) {
      read(path, charset);// 递归调用del方法并取得子目录路径
     }
     else {
      for (String ext : extentions) {
       if (path.endsWith(ext)) {
        transferFile(path);
        break;
       }
      }
     }

    }
   }
  }
 }

 private static void transferFile(String srcFileName) throws IOException {
  FileInputStream fis = new FileInputStream(srcFileName);
  StringBuffer content = new StringBuffer();
  DataInputStream in = new DataInputStream(fis);
  BufferedReader d = new BufferedReader(new InputStreamReader(in, "GBK"));// ,
  String line = null;
  while ((line = d.readLine()) != null)
   content.append(line+"\t\n");
  d.close();
  in.close();
  fis.close();
  FileOutputStream fos = new FileOutputStream(srcFileName);
  fos.write(content.toString().getBytes("UTF-8"));
  fos.flush();
  fos.close();
 } 
}

原创粉丝点击