[code="java"]public class ByteTester {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(259);//00000000 00000000 00000001 00000011
byte [] buff = out.toByteArray();
out.close();
System.out.println("buff.length:="+buff.length);
ByteArrayInputStream in = new ByteArrayInputStream(buff);
int data;
while((data=in.read())!=-1){
System.out.println(data);
}
in.close();
}[/code]
输出结果:buff.length:=1
3
我初步分析是:out.write 只是写入最低位的一个字节,所以读取出才是3
如果是这样的话,写入了数字259 读取的却是3
java io 通过什么保证写入和读出的是一致的呢
数据类型错误,溢出了,你把259改成255以下试下
下面方法可疑达到你的要求
[code="java"]import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Main {
/**
* @param args
*/
// TODO Auto-generated method stub
public static void main(String[] args) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(toByteArray(259, 4));//00000000 00000000 00000001 00000011
byte [] buff = out.toByteArray();
out.close();
System.out.println("buff.length:="+buff.length);
ByteArrayInputStream in = new ByteArrayInputStream(buff);
int data;
byte[] result = new byte[4];
while((in.read(result))!=-1){
System.out.println(toInt(result));
}
in.close();
}
public static byte[] toByteArray(int iSource, int iArrayLen) {
byte[] bLocalArr = new byte[iArrayLen];
for ( int i = 0; (i < 4) && (i < iArrayLen); i++) {
bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );
}
return bLocalArr;
}
// 将byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位
public static int toInt(byte[] bRefArr) {
int iOutcome = 0;
byte bLoop;
for ( int i =0; i<4 ; i++) {
bLoop = bRefArr[i];
iOutcome+= (bLoop & 0xFF) << (8 * i);
}
return iOutcome;
}
}
[/code]