InputStream提供数据读取方法:
·读取单个字节:public abstract int read()throws IOException:
|-返回值:返回读取的字节内容,如果现在已经没有内容。
·将读取的数据保存在字节数组里:public int read(byte [ ]b)throws IOException;
|-返回值:返回读取的数据长度,但是如果已经读到结尾了,返回-1;
·将读取的数据保存在部分字节数组里:public int read(byte [ ]b,int off ,int len)throws IOException;
|-返回值:返回读取的数据长度,但是如果已经读到结尾了,返回-1;
InputStream是一个抽象类,所以如果要进行文件读取使用FileInputStream子类,而这个子类构造:
·构造方法:public FileInputStream(File file)throws FileNotFoundException.
范例1:像数组里读取数据
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Demo {
public static void main(String[] args) throws Exception {
// 1.定义要输入的文件路径
File file = new File("e:" + File.separator + "demo" + File.separator + "my.txt");
// 2.判断路径是否存在才能读取
if (file.exists()) {
// 3.使用InputStream进行读取
InputStream input = new FileInputStream(file);
// 3.进行数据读取
byte[] data = new byte[1024];
int len = input.read(data);
// 4.关闭输入流
input.close();
System.out.println("【" + new String(data, 0, len) + "】");
}
}
}
============分割线============
范例2:单个字节读取,利用while循环读取
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Demo {
public static void main(String[] args) throws Exception {
// 1.定义要输入的文件路径
File file = new File("e:" + File.separator + "demo" + File.separator + "my.txt");
// 2.判断路径是否存在才能读取
if (file.exists()) {
// 3.使用InputStream进行读取
InputStream input = new FileInputStream(file);
// 3.进行数据读取
byte[] data = new byte[1024];
int foot = 0;// 表示数组操作脚标
int temp = 0;// 表示每次接受的字节数据
while ((temp = input.read()) != -1) {
data[foot++] = (byte) temp;// 有内容进行保存
}
// 4.关闭输入流
input.close();
System.out.println("【" + new String(data, 0, foot) + "】");
}
}
}
