Java I/O系统之InputStream

1.InputStream类型

继承自InputStream的流都是用于向程序中输入数据,且数据的单位为字节(8bit);下图中深色为节点流,浅色为处理流。


2.InputStream的基本方法

InputStream的有以下几个的基本用法:

1)        读取一个字节并以整数的形式返回(0~255),如果返回-1已到输入流的末尾。

int read() throws IOException

2)        读取一系列字节并存储到一个数组buffer,返回实际读取的字节数,如果读取前已到输入的末尾返回-1.

int read(byte[] buffer) throws IOException

3)        读取length个字节,并存储一个字节数组buffer,从length位置开始,返回实际读取的字节数,如果读取前以到输入的末尾返回-1.

int read(byte[] buffer, int offset, int length) throws IOException

4)        关闭释放内存资源。

 void close() throws IOException

5)        跳过n个字节不读,返回实际跳过的字节数。

long skip(long n) throws IOException

3.InputStream的例子

package com.owen.io;

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

/**
 * 读取文件 FileInputStream
 * @author OwenWilliam 2016-7-19
 * @since
 * @version v1.0.0
 *
 */
public class TestFileInputStream
{

	public static void main(String[] args)
	{
		int b = 0;
		FileInputStream in = null;
		try
		{
			in = new FileInputStream("E:\\workspace\\Java\\IO\\src\\com\\owen\\io\\TestFileInputStream.java");
		} 
		catch (FileNotFoundException e)
		{
			System.out.println("找不到指定文件");
			System.exit(-1);
		}
		
		try
		{
			long num = 0;
			while ((b = in.read()) != -1)
			{
				System.out.print((char)b);
				num++;
			}
			
			in.close();
			System.out.println();
			System.out.println("其读取了 " + num + " 个字节");
		}
		catch (IOException el)
		{
			System.out.println("文件读取错误");
			System.exit(-1);
		}

	}

}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值