java byte 与操作_java 流与 byte[] 的互转操作

1. InputStream -> byte[]引入 apache.commons.is 包import org.apache.commons.io.IOUtils;byte[] bytes = IOUtils.toByteArray(inputStream);2. byte[] -> InputStreamInputStream inputStream = new ByteArray...
摘要由CSDN通过智能技术生成

1. InputStream -> byte[]

引入 apache.commons.is 包

import org.apache.commons.io.IOUtils;

byte[] bytes = IOUtils.toByteArray(inputStream);

2. byte[] -> InputStream

InputStream inputStream = new ByteArrayInputStream(bytes);

补充知识:byte[]与各种数据类型互相转换示例

在socket开发过程中,通常需要将一些具体的值(这些值可能是各种JAVA类型)转化为byte[]类型,为此我总结了如下这个示例,贴出来,以便经常翻看

public class TestCase {

/**

* short到字节数组的转换.

*/

public static byte[] shortToByte(short number) {

int temp = number;

byte[] b = new byte[2];

for (int i = 0; i < b.length; i++) {

b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位

temp = temp >> 8;// 向右移8位

}

return b;

}

/**

* 字节数组到short的转换.

*/

public static short byteToShort(byte[] b) {

short s = 0;

short s0 = (short) (b[0] & 0xff);// 最低位

short s1 = (short) (b[1] & 0xff);

s1 <<= 8;

s = (short) (s0 | s1);

return s;

}

/**

* int到字节数组的转换.

*/

public static byte[] intToByte(int number) {

int temp = number;

byte[] b = new byte[4];

for (int i = 0; i < b.length; i++) {

b[i

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值