Java IO流 打印流 PrintStream PrintWriter
Java IO流 序列化流 ObjectOutputStream ObjectInputStream
Java IO流 缓冲流 BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
Java IO流 字符流 目录拷贝
Java IO流 字符流 FileWriter
Java IO流 字符流 FileReader
Java IO流 字节流 FileInputStream
Java IO流 字节流 FileOutputStream
FileInputStream 继承自抽象类InputStream,用于实现从文件向内存中写入数据
创建对象
创建FileInputStream 对象,相当于再内存与文件之间打开一个通道
note:
如果文件不存在,直接报错
String filePath = "src/main/java/io_stream/a.txt";
FileInputStream fis = new FileInputStream(filePath);
文件读取
FileInputStream 的读取方式有四种
read() 读取一个字节
read(byte b[]) 读取到的数据放到字节数组b中
read(byte b[], int off, int len) 读取到的数据放到字节数组b中,从off开始,连续len个数据,超出范围不写入b中
readAllBytes() 读取所有数据,返回一个字节数组
note:
文件中内容为 abcdefg
read()读取到最后会返回-1,可作为读取结束条件
读取结束之后要调用close()方法,关闭流
public class ByteStream {
public static void main(String[] args) throws IOException {
String filePath = "src/main/java/io_stream/a.txt";
testFileInputStream(filePath);
}
public static void testFileInputStream(String filePath) throws IOException {
FileInputStream fis = new FileInputStream(filePath);
// read()方法测试 每次运行一种方法测试,其他要注释掉,以免影响结果
int b;
while((b = fis.read()) != -1){
System.out.print((char)b); // 打印 abcdefg
}
// read(byte b[])方法测试
byte[] bytes = new byte[7];
fis.read(bytes);
for (byte b : bytes) {
System.out.print((char)b); // 打印 abcdefg
}
// read(byte b[], int off, int len)方法测试
byte[] bytes = new byte[7];
fis.read(bytes, 0, 3);
for (byte b : bytes) {
System.out.print((char)b); // 打印 abc
}
// readAllBytes()方法测试
byte[] allBytes = fis.readAllBytes();
for (byte b : allBytes) {
System.out.print((char)b); // 打印 abcdefg
}
fis.close();
}
}