为什么存在字节流和字符流?
我们知道英文字母存储是以utf-8进行的,一个字母占用一个字节。汉字如果以utf-8存储的话,占用3个字节。以gbk存储的话,占用两个字节。如果我们在读字节的时候一个字节一个字节读,那读到的字节就会显示乱码。例如:
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("fos.txt");
int by;
while ((by = fis.read()) != -1){
System.out.print((char)by);
}
fis.close();
}
fox.txt中的原始内容为:中国iloveyou
程序读到的内容为:ä¸å›½iloveyou
所以,由此产生了字符流:
为什么写字节显示正确呢,是因为汉字有标志为-,所以能够区分是否是汉字存储。
String s = "中国";
byte[] bytes = s.getBytes();
System.out.println(Arrays.toString(bytes));
//[-28, -72, -83, -27, -101, -67]
byte[] bytes1 = s.getBytes("GBK");
System.out.println(Arrays.toString(bytes1));
//[-42, -48, -71, -6]
String ss = new String(bytes1,"GBK");
//涓浗
System.out.println(ss);