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