2016年02月04日 Java I/O 浏览(201)

Java将GBK文件批量转成UTF-8文件的源代码

GBK文件批量转成UTF-8文件代码如下:

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.Writer;
/**
 * @from everycoding.com
 */
public class GBKFileToUTF8FileTester {
    public static void main(String[] args) throws IOException {
        File dir = new File("D:/my/gbkDir");
        System.out.println(dir.exists());
        if (dir.exists()) {
            for (File file : dir.listFiles()) {
                transferFile(file.getPath(),"D:/my/utf8Dir/"+file.getName());
            }
        }
    }
    
    private static void transferFile(String srcFileName, String destFileName) throws IOException {
        String line_separator = System.getProperty("line.separator");
        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 + line_separator);
        }
        d.close();
        in.close();
        fis.close();

        Writer ow = new OutputStreamWriter(new FileOutputStream(destFileName), "utf-8");
        ow.write(content.toString());
        ow.close();
    }
}


用户头像