编码:字符编码为字节
byte[] getBytes()
byte[] getBytes(String charsetName);
解码:字节解码为字符
String(byte[] b);
String(byte[] b,String charsetName)
操作:
编码:留神输入的时候用类调用办法 toString()
String s = "中国";
byte[] by = s.getBytes();
//byte[] by = s.getBytes(BGK)
//byte[] by = s.getBytes(UTF-8)
sout(Array.toString(by));
解码:留神解码和编码的形式要统一能力失去正确的字符串
String ss = String(by);
//String sss = String(by,GBK)
//String sss = String(by,UTF-8)
sout(ss);
二、字符流的编码和解码
public abstract class Writer
public abstract class Reader
.
public classs OutputStreamWriter extends Writer
public class InputStreamReader extends Reader
构造函数:
OutputStreamWriter(OutputStream out)
OutputStreamWriter(OutputStream out,String charsetName)
InputStreamReader(InputStream in)
InputStreamReader(InputStream in,String charsetName)
操作:
创建对象 + 写数据
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("s.txt"));
osw.write("中国");
osw.close();
创建对象 + 读数据
读数据也有两种形式:一次读一个字符 / 一次读一个字符数组
形式一:
InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\sa\\s.txt"))
int ch;
while((ch=isr.read())!=-1){Sout((char)ch);
}
isr.close();
形式二:
InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\sa\\s.txt"))
char[] ch = new char[1024];
int len;
while ((len = isr.read(ch))!=-1){Sout(String(ch,0,len));
}
isr.close();