/*
* String(byte[] bytes, String charsetName):通過指定的字符集解碼字節數組
* byte[] getBytes(String charsetName):使用指定的字符集合把字符串編碼為字節數組
*
* 編碼:把看得懂的變成看不懂的
* String -- byte[]
*
* 解碼:把看不懂的變成看得懂的
* byte[] -- String
*
* 舉例:諜戰片(發電報,接電報)
*
* 碼錶:小本子
* 字符數值
*
* 要發送一段文字:
* 今天晚上在老地方見
*
* 發送端:今 -- 數值 -- 二進制 -- 發出去
* 接收端:接收 -- 二進制 -- 十進制 -- 數值 -- 字符 -- 今
*
* 今天晚上在老地方見
*
* 編碼問題簡單,只要編碼解碼的格式是一致的。
*/
public class StringDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "你好";
// String -- byte[]
byte[] bys = s.getBytes(); // [-60, -29, -70, -61]
// byte[] bys = s.getBytes("GBK");// [-60, -29, -70, -61]
// byte[] bys = s.getBytes("UTF-8");// [-28, -67, -96, -27, -91, -67]
System.out.println(Arrays.toString(bys));
// byte[] -- String
String ss = new String(bys); // 你好
// String ss = new String(bys, "GBK"); // 你好
// String ss = new String(bys, "UTF-8"); // ???
System.out.println(ss);
}
}
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
// 創建字節輸入流對象
FileInputStream fis = new FileInputStream("a.txt");
// 讀取數據
// int by = 0;
// while ((by = fis.read()) != -1) {
// System.out.print((char) by);
// }
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
System.out.print(new String(bys, 0, len));
}
// 釋放資源
fis.close();
}
}
閱讀更多 java課堂 的文章