您好,登錄后才能下訂單哦!
字節(jié)數(shù)組輸出流,無需添加目的地,因為數(shù)據(jù)會被自動輸入內(nèi)存的緩沖區(qū),需通過
.toByteArray()或.toString()拿到數(shù)據(jù)
因為需要使用子類ByteArrayOutputStream的新方法,所以不能寫父類OutputStream對象
ByteArrayOutputStream os=new ByteArrayOutputStream();
因為數(shù)據(jù)寫入了緩沖區(qū),所以需要通過.toByteArray()和.toString()手動拿取
步驟:
創(chuàng)建目的地字節(jié)數(shù)組(用來存放從緩沖區(qū)拿來的數(shù)據(jù)): Byte[] last=null;
選擇流: ByteArrayOutputStream os;
編碼:字符串到字節(jié)
操作:os.write(byte[],0,byte,length)寫入
獲取數(shù)據(jù):last=os.toByteArray();
System.out.println(new String(last,0,last.length)//或last.length可替換成os.size()
解碼
public class test{
public static void main(String[]args)
{
//創(chuàng)建目的地
byte[] last=null;
//選擇流(新增方法)
ByteArrayOutputStream os=null; //不用OutputStream,是因為要用子類ByteArrayOutputStream的新增方法
try {
os =new ByteArrayOutputStream();
String s="hello world";
byte[] data=s.getBytes(); //編碼,字符串到字符數(shù)組
os.write(data,0,data.length);
os.flush();
//獲取數(shù)據(jù)
last=os.toByteArray();
System.out.println(last.length);
System.out.println(last.length+"---"+new String(last,0,last.length));//或者os.size()
}catch(IOException e)
{
e.printStackTrace();
}
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。