首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

跪求:把GBK字符串写入到UTF-8文本文件中不为乱码的方法!解决方案

2012-04-12 
跪求:把GBK字符串写入到UTF-8文本文件中不为乱码的方法!比如,一个文本文件A.txt里面有“中华人民共和国”这

跪求:把GBK字符串写入到UTF-8文本文件中不为乱码的方法!
比如,一个文本文件A.txt里面有“中华人民共和国”这句话,这个文本文件保存时是采用GBK编码方式。现在要读出这个字符串,把这句话写入到B.txt中,注意:这里B.txt是以UTF-8方式保存的。正常情况下写进去后,B.TXT中出现????????????。采用

Java code
byte[] bs = str.getBytes();newstr = new String(bs, "UTF-8");
方法无效。
采用
Java code
InputStreamReader read = new InputStreamReader(new FileInputStream(A.txt),"UTF-8");         BufferedReader br = new BufferedReader(read);        BufferedWriter bw = new BufferedWriter(new FileWriter(B.txt));
也无效!请高手帮忙

[解决办法]
试试这段程序:
Java code
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;public class FileProcess {    public static void main(String[] args) {        FileInputStream fis = null;        FileOutputStream fos = null;        try{            fis = new FileInputStream(new File("d:\\a.txt"));            fos = new FileOutputStream(new File("d:\\b.txt"));            byte[] buffer = new byte[fis.available()];            fis.read(buffer);            String str = new String(buffer, "GBK");            fos.write(str.getBytes("utf-8"));        }catch(Exception e){            e.printStackTrace();        }finally{            if(fis != null){                try{                    fis.close();                }catch(Exception e){                                    }            }            if(fos != null){                try{                    fos.close();                }catch(Exception e){                                    }            }        }    }}
[解决办法]
我试了一下,好像没有问题,你看看

Java code
import java.io.BufferedReader;import java.io.Closeable;import java.io.File;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;public class Test01 {        public static void main(String[] args) {        File in = new File("test.txt");        File out = new File("test2.txt");        BufferedReader br = null;        OutputStreamWriter ow = null;                try {            br = new BufferedReader(new FileReader(in));            ow = new OutputStreamWriter(new FileOutputStream(out), "utf-8");            for(String str = null, separator = System.getProperty("line.separator"); (str = br.readLine()) != null;) {                ow.write(str);                ow.write(separator);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            close(br);            close(ow);        }        System.out.println("ok");    }    private static void close(Closeable stream) {        try {            stream.close();        } catch (IOException e) {            e.printStackTrace();        }    }} 

热点排行