楼主可以测试,推断下结果: 首先,OutputStream的write(int b)方法很明确的说明:写入的字节是参数 b 的八个低位,b 的 24 个高位将被忽略;也就是说如果b是0-255的数字就不会出现问题,但显然,int是4个字节长度; 所以OutputStream要想完整的写入一个int值,需要做些处理;其次,InputStream的read()是从输入流中读取数据的下一个字节,注意是一个字节; 这里需要注意:在流中没有 有符号(一个有符号字节表示范围 -128-127)的概念(但java的byte, short, int, char等基本类型是有符号的),字节都是无符号数字(一个无符号字节表示范围 0-255),但流是用-1来区分是否结束的,显然-1超出了1个无符号字节表示范围,所以返回是个int;楼主看了上面是否清楚了上面代码的做法?简单示例:public static void main(String[] args) throws IOException { writeNoProcessedIntValue(); writeProcessedIntValue(); } public static void writeNoProcessedIntValue() throws IOException{ OutputStream out = new FileOutputStream("Text1.bat"); out.write(100000); out.close();
InputStream in = new FileInputStream("Text1.bat"); int readByte = in.read(); in.close(); System.out.println("No-processed : " + readByte); }
public static void writeProcessedIntValue() throws IOException{ OutputStream out = new FileOutputStream("Text2.bat"); out.write(100000>>24); out.write(100000>>16); out.write(100000>>8); out.write(100000>>0); out.close();
InputStream in = new FileInputStream("Text2.bat"); int readByte1 = in.read(); int readByte2 = in.read(); int readByte3 = in.read(); int readByte4 = in.read(); in.close();
首先,OutputStream的write(int b)方法很明确的说明:写入的字节是参数 b 的八个低位,b 的 24 个高位将被忽略;也就是说如果b是0-255的数字就不会出现问题,但显然,int是4个字节长度;
所以OutputStream要想完整的写入一个int值,需要做些处理;其次,InputStream的read()是从输入流中读取数据的下一个字节,注意是一个字节;
这里需要注意:在流中没有 有符号(一个有符号字节表示范围 -128-127)的概念(但java的byte, short, int, char等基本类型是有符号的),字节都是无符号数字(一个无符号字节表示范围 0-255),但流是用-1来区分是否结束的,显然-1超出了1个无符号字节表示范围,所以返回是个int;楼主看了上面是否清楚了上面代码的做法?简单示例:public static void main(String[] args) throws IOException {
writeNoProcessedIntValue();
writeProcessedIntValue();
} public static void writeNoProcessedIntValue() throws IOException{
OutputStream out = new FileOutputStream("Text1.bat");
out.write(100000);
out.close();
InputStream in = new FileInputStream("Text1.bat");
int readByte = in.read();
in.close();
System.out.println("No-processed : " + readByte);
}
public static void writeProcessedIntValue() throws IOException{
OutputStream out = new FileOutputStream("Text2.bat");
out.write(100000>>24);
out.write(100000>>16);
out.write(100000>>8);
out.write(100000>>0);
out.close();
InputStream in = new FileInputStream("Text2.bat");
int readByte1 = in.read();
int readByte2 = in.read();
int readByte3 = in.read();
int readByte4 = in.read();
in.close();
System.out.println("Processed : " + ((readByte1 << 24) + (readByte2 << 16) + (readByte3 << 8) + (readByte4 << 0)));
}
至于这个整数为什么刚好是流数据的长度,那取决于发送方和接收方的约定。跟Java本身的API无关。