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();
		}
	}
}

 

     有两点需要解释一下:

 

     对字节数组输入流( 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)方法来读取文件以提高效率。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值