Java 字节输入流: InputStream

InputStream类的定义

public abstract class InputStream
extends Object
implements Closeable

常用方法

读取数据到字节数组中:
如果字节数组大于数据的大小, 返回的是该数据的长度
如果数据大于字节数组的大小, 返回的是该数组的长度
如果没有数据了, 还要进行读取,则返回 -1

public int read(byte[] b)
         throws IOException

读取单个字节到字节数组中:
每次取出一个字符
如果没有数据了, 还要进行读取,则返回 -1

public abstract int read()
                  throws IOException

读取部分数据到字节数组中:

public int read(byte[] b,
                int off,
                int len)
         throws IOException

InputStream 对文件操作

因为InputStream是抽象类,所以如果要进行对文件的操作, 则使用FileInputStream类进行实现
在这里插入图片描述

案例: 实现文件信息的读取

package com.cwq.beyond;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class test22 {
	public static void main(String[] args) throws Exception {
		File file = new File("D:" + File.separator + "HelloDemo.txt"); // 通过File 类定义文件路径
		if (file.exists()) {
			InputStream input = new FileInputStream(file);
			byte data [] = new byte[1000];  // 取信息的勺子
			int len = input.read(data);  // 将数据读取到了字节数组之中
			System.out.println("读取内容:["+new String(data,0,len)+"]");
			input.close();
		}
	}

}

在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_大木_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值