一道JAVA IO面试题

By Lee - Last updated: 星期五, 一月 31, 2014 Leave a Comment

将一个GBK编码的文本文件转存为一个UTF-8编码的文本文件。

由于很久没用IO流了,当时的代码写的相当混乱,现在整理如下:

import java.io.*;

public class ChangeEncoding {

    public static void changeEncoding (String inEncoding, String outEncoding,

            String inFileName, String outFileName)  throws IOException {

        BufferedReader reader = new BufferedReader(

            new InputStreamReader(

            new FileInputStream(inFileName), inEncoding));

        BufferedWriter writer = new BufferedWriter(

            new OutputStreamWriter(

            new FileOutputStream(outFileName), outEncoding));

        String s = null;

        while ((s = reader.readLine()) != null) {

            writer.write(s, 0, s.length());

            writer.newLine();

        writer.flush();

        writer.close();

        reader.close();

    public static void main(String[] args) {

        try {

            changeEncoding(“GBK”, “UTF-8″, “gbk.txt”, “utf8.txt”);

        } catch (IOException e) {

            System.out.println(“转换失败,原因:” + e.getMessage());

PS:BufferedWriter输出的UTF-8文件是无BOM格式编码的。

转自 一道JAVA IO面试题 – 老马睡不醒 – 博客园.