您的位置:首页 > 编程语言 > Java开发

java字节输入流

2008-12-30 16:37 260 查看
学习了一下Java的字节输入流,下面是其使用入门的几个小例子。

Java代码

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class inputStreamTest
{
public static void main(String[] args)
{
byteArrayInputStream();

fileInputStreamTest();
}

public static void byteArrayInputStream()
{
byte[] buffer = new byte[]{3, -1, 36, -9, 20};
ByteArrayInputStream in = new ByteArrayInputStream(buffer);

// int data = in.read();
// while(data != -1)
// {
//输出结果为:3 255 36 247 20
// System.out.print(data + " ");
// data = in.read();
// }

byte[] buff = new byte[buffer.length];
try
{
in.read(buff);
//(需要将前面的部分注释掉)输出结果为:3 -1 36 -9 20
for(int i=0; i<buff.length; i++)
System.out.print(buff[i] + " ");

} catch(IOException e)
{
e.printStackTrace();
}

try
{
in.close();

} catch (IOException e) {
e.printStackTrace();
}
}

public static void fileInputStreamTest()
{
System.out.println();
try
{
//a.txt中内容为:abc中国def
FileInputStream is = new FileInputStream("C:\\a.txt");

int data = is.read();

//输出结果为:97 98 99 214 208 185 250 100 101 102
while(data != -1)
{
System.out.print(data + " ");
data = is.read();
}

is.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class inputStreamTest { public static void main(String[] args) { byteArrayInputStream(); fileInputStreamTest(); } public static void byteArrayInputStream() { byte[] buffer = new byte[]{3, -1, 36, -9, 20}; ByteArrayInputStream in = new ByteArrayInputStream(buffer); // int data = in.read(); // while(data != -1) // { //输出结果为:3 255 36 247 20 // System.out.print(data + " "); // data = in.read(); // } byte[] buff = new byte[buffer.length]; try { in.read(buff); //(需要将前面的部分注释掉)输出结果为:3 -1 36 -9 20 for(int i=0; i<buff.length; i++) System.out.print(buff[i] + " "); } catch(IOException e) { e.printStackTrace(); } try { in.close(); } catch (IOException e) { e.printStackTrace(); } } public static void fileInputStreamTest() { System.out.println(); try { //a.txt中内容为:abc中国def FileInputStream is = new FileInputStream("C:\\a.txt"); int data = is.read(); //输出结果为:97 98 99 214 208 185 250 100 101 102 while(data != -1) { System.out.print(data + " "); data = is.read(); } is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

有两点需要解释一下:

对字节数组输入流( ByteArrayInputStream),对于字节类型的-9,二进制为11110111,转换为int类型(int data = in.read();)的二进制形式为00000000 00000000 00000000 11110111,因此字节类型的-9转换为int类型的247,也就会输出247. 对于-1,也是类似的情况,转换为了255.

对文件输入流(FileInputStream),字符"a"、"b"、"c"的GBK编码各占1个字节,分别是97、98、99,而"中"和"国"的 GBK编码各占2个字节,分别是214和208,以及185和250,所以才会有上面的输出结果。当然,也可以用read(byte[] buff)方法来读取文件以提高效率。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: