InputStream类介绍
抽象类,子类FileInputStream
方法介绍
int read()、int read(byte[ ] b)、int read(byte[ ] b,int off,int len)
int read()
一次只读一个字节的数据,返回值是0~255的一个 int型整数,到最后没有可用字节时返回:-1
问题:读取一个字节,为什么不直接返回byte类型的数据?
答案:链接
代码示例
public static void main(String[] args) throws IOException {
//File对象对文件或文件夹目录的抽象表示,与系统中某个文件或者文件夹建立连接
//目录以及文件需要自己创建好
File file = new File("C:\\Users\\Beshare\\Desktop\\demo\\test.txt");
InputStream inputStream = new FileInputStream(file);
//申明一个字节数组(用来保存读取到的数据)
byte[] b = new byte[1024];
int temp;
int footer = 0;
//一次只读一个字节
while ((temp = inputStream.read()) != -1)
b[footer++] = (byte)temp;
String str = new String(b);
}
int read(byte[ ] b)
从数据流读取一些字节并保存到缓冲数组b中,并返回缓冲区中数据的长度,如果没有数据了则返回:-1
代码
public static void main(String[] args) throws IOException {
//文件目录及文件需要自己创建
File file = new File("C:\\Users\\Beshare\\Desktop\\demo\\test.txt");
//利用FileInputStream.read(byte b)来实现
InputStream inputStream = new FileInputStream(file);
//设置缓冲区
byte[]b = new byte[2];
StringBuilder stringBuilder= new StringBuilder();
int length;
while((length = inputStream.read(b)) !=-1) {
stringBuilder.append(new String(b,0,length));
}
System.out.println(stringBuilder);
}
int read(byte[ ] b,int off,int len)
从数据流读取一些字节并保存到缓冲数组b中(从坐标为off的地方存储,每次存的长度为len,并返回缓冲区中所存储的数据的长度(如果没有了则返回-1)
代码
public static void main(String[] args) throws IOException {
//文件目录及文件需要自己创建
File file = new File("C:\\Users\\Beshare\\Desktop\\demo\\test.txt");
//利用FileInputStream.read(byte b)来实现
InputStream inputStream = new FileInputStream(file);
//设置缓冲区
byte[]b = new byte[3];
StringBuilder stringBuilder= new StringBuilder();
int length;
while((length = inputStream.read(b,1,2)) !=-1) {
//上面的缓冲数组是从1开始的(off:1),则下面数组从1开始解码(offset:1)
stringBuilder.append(new String(b,1,length));
}
System.out.println(stringBuilder);
}
补充
构造器String(byte bytes[ ], int offset, int length ):
bytes: 要解码为字符的 byte
offset: 要解码的第一个 byte 的索引
length: 要解码的 byte 数 的长度
0:解码是 空格