您的位置 首页 java

java字节数组流

/**

* 测试字节数组流 Byte Array InputStream /ByteArrayOutputStream

* 节点流,存取内存中的字节数组/数据源

*/

public class ByteArrayStream1 {

public static void main(String[] args) {

byte[] bytes = “safdssafd”.getBytes();

try(ByteArrayInputStream bais = new ByteArrayInputStream(bytes)){

//以byte[]数组为数据源,不同于 FileInputStream 从磁盘中读取文件作为数据源

for (int b = bais.read();b!=-1;b = bais.read()){

System.out.write(b);

//直接调用out将每一个字节输出到控制台

}

System.out.flush();

//结果为:safdssafd

}catch ( Exception e){

e.printStackTrace();

}

// for (byte b :

// bytes) {

// System.out.println((char)b);

// }

//结果一样

System.out.println();

bytes = “GBK字符集中,中文字符需要两个字节来表示”. getBytes ();

try(ByteArrayInputStream bais = new ByteArrayInputStream( bytes )){

for (int b = bais.read();b!=-1;b = bais.read()){

System.out.write(b);

//UTF-8字符集中每个汉字用三个字节来表示,每一个单独的字节无法表达正确的含义

}

System.out.flush();

//结果为:GBK字符集中,中文字符需要两个字节来表示

//out将字节交给控制台后,控制台对接收到的byte[]数组进行解码,将得到的中文显示出来

}catch (Exception e){

e.printStackTrace();

}

System.out.println();

try(ByteArrayOutputStream baos = new ByteArrayOutputStream()){

//字节数组输出流构造器不必须要有参数

baos.write(97);

//.write(int b)因为是字节流所以b超过255在存储时会溢出%255

baos.write(‘b’);

// char 类型可以自动转换int/向上转换,这里write方法将’b’自动转换为98存储

baos.write(‘c’);

baos.flush();

bytes = baos.toByteArray();

//.toByteArray()方法将写入的字节作为数组返回

for (byte b:

bytes) {

System.out.print((char) b);

}

//结果为:abc

}catch (Exception e){

e.printStackTrace();

}

}

}

文章来源:智云一二三科技

文章标题:java字节数组流

文章地址:https://www.zhihuclub.com/175488.shtml

关于作者: 智云科技

热门文章

网站地图