例:
import java.io.*;
class EncodeStream
{
public static void main(String[] args)throws IOException
{
//writeText();
readText();
}
public static void readText()throws IOException
{
InputStreamReader isr = new InputStreamReader(new FileInputStream("gbk.txt"), "utf-8");
char[] buf = new char[10];//注意:是char型数组
int len = isr.read(buf);//读数据放到数组中
String str = new String(buf, 0, len);//放到字符中
System.out.println(str);
isr.close();
}
public static void writeText()throws IOException
{
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("utf.txt"), "utf-8");
osw.write("你好");//写入数据
osw.close();
}
}
------------------------------------------------------------------------------------------------------------------------------
String ----> byte[] str.getBytes[];
byte[] ----> String new String(byte[]);
例:
import java.util.*;
class EncodeDemo
{
public static void main(String[] args)throws Exception
{
String s = "你好";
byte[] b1 = s.getBytes("GBK");//默认是GBK编码
System.out.println( Arrays.toString(b1) );//把数组变成字符串
String s1 = new String(b1,"utf-8");//解码
System.out.println("s1="+s1);//输出
//对s1进行iso8859-1解码
byte[] b2 = s1.getBytes("utf-8");
System.out.println(Arrays.toString(b2));
String s2 = new String(b2, "GBK");
System.out.println("s2="+s2);
//注意,iso8859-1可以这样解码,因为此编码表不识别中文,
//utf-8不可以这样解码,因为此编码表识别中文
}
}
--------------------------------------------------------------------------------------------
“联通”问题:
class EncodeDemo2
{
public static void main(String[] args)throws Exception
{
String s = "联通";
byte[] by = s.getBytes("gbk");//编码
for(byte b : by) //输出二进制码
{
System.out.println(Integer.toBinaryString(b&255));//取二进制后8位
}
}
}
-----------------------------------------------------------------------------------------------
个人总结:记住几种常见的编码表,如UTF-8、 GBK、 ISO8859-1等,写入文件通过
转换流OutputStreamWriter和InputStreamReader来实现,注意编码和解码使用的方法
是str.getBytes()和new String(byte[]),"联通"这个问题出现主要是gbk和utf-8之间编码的
区别,具体可查API文档中utf-8的编码形式