文件编码批量转换[代码]

package com.hmilyld.frame.tools;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
 
import javax.swing.JTextArea;
 
public class ConvertStr {
 
    
private String NEW_FOLDER;// 需要保存的文件路径
    private String FILE_PATH;// 原文件路径
    private String oldEncode;// 原编码
    private String newEncode;// 转换后的编码
    private String houzhui;// 文件后缀名称
    private JTextArea view;
 
    
public ConvertStr(String filePath, String newFolder, String oldEncode,
            String newEncode, String houzhui, JTextArea view) {
        
this.NEW_FOLDER = newFolder;
        
this.FILE_PATH = filePath;
        
this.oldEncode = oldEncode;
        
this.newEncode = newEncode;
        
this.houzhui = houzhui;
        
this.view = view;
    }
 
    
/**
     * 查找出所有文件
     *
     * 
@param path
     * 
@throws Exception
     
*/
    
public void listFile(String path) throws Exception {
        File file 
= new File(path);
        File[] f 
= file.listFiles();
        
for (int i = 0; i < f.length; i++) {
            
if (f[i].isDirectory()) {
                
// 如果为目录,则再次遍历该目录
                this.listFile(f[i].getPath());
            } 
else {
                
// 如果为文件,则判断是否为指定后缀名称
                String name = f[i].getName();
                
if (name.substring(name.length() - houzhui.length(),
                        name.length()).equals(houzhui)) {
                    
this.convertFile(path, name);
                }
            }
        }
    }
 
    
/**
     * 转换编码,并写入新文件
     *
     * 
@param filePath
     * 
@param fileName
     * 
@throws Exception
     
*/
    
private void convertFile(String filePath, String fileName) throws Exception {
        filePath 
= filePath + "\\";
        
// 重写FileReader类,让file可以以指定编码格式读入
        FileReaderByEncode file = new FileReaderByEncode(filePath + fileName,
                oldEncode);
        BufferedReader br 
= new BufferedReader(file);
        String temp 
= "";
        StringBuffer sb 
= new StringBuffer();
        
while ((temp = br.readLine()) != null) {
            sb.append(temp 
+ '\n');
        }
        br.close();
        temp 
= sb.toString();
        filePath 
= filePath.replace(FILE_PATH, NEW_FOLDER);
        File tempFile 
= new File(filePath);
        
// 检查指定目录中是否存在目录,没有则新建
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        
// 按照编码写出该文件
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(
                filePath 
+ fileName), newEncode);
        out.write(temp);
        out.flush();
        out.close();
        view.setText(filePath 
+ fileName + " 转换完成" + '\n' + view.getText());
    }
}
posted @ 2009-10-12 17:12  星尘  阅读(913)  评论(1编辑  收藏  举报