Java-文件转码方法

时间:2021-09-29 20:05:55

http://blog.csdn.net/zhengqiqiqinqin/article/details/12621201

法一:java.lang.string

    //法一: xx编码-->new String(byte[]b,Charset xx)-->Stirng.getBytes(Charset yy)-->yy编码
public static void method_1() throws Exception
{
FileInputStream fis
=new FileInputStream ("F:\\test\\test.txt");
File f
=new File("F:\\test\\copy-test2.txt");
if(!f.exists())
f.createNewFile();
FileOutputStream fos
=new FileOutputStream(f);

byte [] b=new byte[10];
int len=0;
while((len=fis.read(b))!=-1)
{
//思路:GB2312 到UTF-8,必须通过一个中间编码介质,这里是String
//将字节数组转换为string (其编码与操作系统一样是GBK)
//再将String转成其他编码的字节数组
String s=new String(b,0,len,"GB2312");
b
=s.getBytes("UTF-8");
//fos.write(b,0,len);注意:这里是错误的,因为转码后的字节数组的长度变了,不是原来长度的字节数组
fos.write(b);
}
if(fos!=null)
fos.close();
if(fis!=null)
fis.close();
}

法二:java.io.InputStreamReader/OutputStreamWriter:桥转换

//法二(推荐):【IO流】xx编码-->inputstreamreader(file,"xx")--->outputStreamWriter(file,"yy")-->yy编码
public static void method_2()throws Exception
{
FileInputStream fis
=new FileInputStream ("F:\\test\\test.txt");
File f
=new File("F:\\test\\copy-test.txt");
if(!f.exists())
f.createNewFile();
FileOutputStream fos
=new FileOutputStream(f);
//io流转接
InputStreamReader isr=new InputStreamReader(fis,"GB2312");
OutputStreamWriter osw
=new OutputStreamWriter(fos,"UTF-8");
//读取:
char [] cs=new char[1024];
int len=0;
while((len=isr.read(cs))!=-1)
{
osw.write(cs,
0,len);
}
//关闭流
osw.flush();
osw.close();
isr.close();
}

方法三:java.nio.Charset