java字節(jié)數(shù)組流
/**
* 測試字節(jié)數(shù)組流ByteArrayInputStream/ByteArrayOutputStream
* 節(jié)點流,存取內(nèi)存中的字節(jié)數(shù)組/數(shù)據(jù)源
*/
public class ByteArrayStream1 {
? ?public static void main(String[] args) {
? ? ? ?byte[] bytes = "safdssafd".getBytes();
? ? ? ?try(ByteArrayInputStream bais = new ByteArrayInputStream(bytes)){
? ? ? ? ? ?//以byte[]數(shù)組為數(shù)據(jù)源,不同于FileInputStream從磁盤中讀取文件作為數(shù)據(jù)源
? ? ? ? ? ?for (int b = bais.read();b!=-1;b = bais.read()){
? ? ? ? ? ? ? ?System.out.write(b);
? ? ? ? ? ? ? ?//直接調(diào)用out將每一個字節(jié)輸出到控制臺
? ? ? ? ? ?}
? ? ? ? ? ?System.out.flush();
? ? ? ? ? ?//結(jié)果為:safdssafd
? ? ? ?}catch (Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
// ? ? ? ?for (byte b :
// ? ? ? ? ? ? ? ?bytes) {
// ? ? ? ? ? ?System.out.println((char)b);
// ? ? ? ?}
? ? ? ?//結(jié)果一樣
? ? ? ?
? ? ? ?System.out.println();
? ? ? ?bytes = "GBK字符集中,中文字符需要兩個字節(jié)來表示".getBytes();
? ? ? ?try(ByteArrayInputStream bais = new ByteArrayInputStream(bytes)){
? ? ? ? ? ?for (int b = bais.read();b!=-1;b = bais.read()){
? ? ? ? ? ? ? ?System.out.write(b);
? ? ? ? ? ? ? ?//UTF-8字符集中每個漢字用三個字節(jié)來表示,每一個單獨的字節(jié)無法表達正確的含義
? ? ? ? ? ?}
? ? ? ? ? ?System.out.flush();
? ? ? ? ? ?//結(jié)果為:GBK字符集中,中文字符需要兩個字節(jié)來表示
? ? ? ? ? ?//out將字節(jié)交給控制臺后,控制臺對接收到的byte[]數(shù)組進行解碼,將得到的中文顯示出來
? ? ? ?}catch (Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
? ? ? ?System.out.println();
? ? ? ?try(ByteArrayOutputStream baos = new ByteArrayOutputStream()){
? ? ? ? ? ?//字節(jié)數(shù)組輸出流構(gòu)造器不必須要有參數(shù)
? ? ? ? ? ?baos.write(97);
? ? ? ? ? ?//.write(int b)因為是字節(jié)流所以b超過255在存儲時會溢出%255
? ? ? ? ? ?baos.write('b');
? ? ? ? ? ?//char類型可以自動轉(zhuǎn)換int/向上轉(zhuǎn)換,這里write方法將'b'自動轉(zhuǎn)換為98存儲
? ? ? ? ? ?baos.write('c');
? ? ? ? ? ?baos.flush();
? ? ? ? ? ?bytes = baos.toByteArray();
? ? ? ? ? ?//.toByteArray()方法將寫入的字節(jié)作為數(shù)組返回
? ? ? ? ? ?for (byte b:
? ? ? ? ? ? ? ? bytes) {
? ? ? ? ? ? ? ?System.out.print((char) b);
? ? ? ? ? ?}
? ? ? ? ? ?//結(jié)果為:abc
? ? ? ?}catch (Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
? ?}
}