一、InputStream(字节输入流基类)
1、读操作介绍
int read = inputStream.read();
//每次读取一个字节,返回的结果为对应字节的数据
inputStream.read(byte[] arr);
//批量读取数据,将数据读入到arr的byte数组中,返回值为int类型,表示读取的有效数据的个数
int read(byte b[], int off, int len);
//批量读取数据,b[] 表示的是数据读入的缓存地址,off表示读入的缓存起始位置,len表示从起始位置开始写入的数量,
//read方法返回值表示读取有效数据个数
2、常用方法
3、字节输入流的操作步骤
步骤1:打开特定类型的输入流,可能会抛出FileNotFoundException
FileInputStream inputStream = new FileInputStream(path);
步骤2:读取数据操作,-1表示读取结束,可能会抛出IOException异常
int read = inputStream.read();
步骤3:关闭流,可能会抛出IOException异常
inputStream.close();
public class IOdemo {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\lo\\Desktop\\ss.txt";
//1.打开特定类型的输入流,可能会抛异常(FileNotFoundException)
FileInputStream inputStream = new FileInputStream(path);
//2.读取数据
//每次读取一个字节,返回的结果为对应数据的数据
int read = inputStream.read();
System.out.println((char) read);
byte[] bytes = new byte[20];
//批量读取数据
int read1 = inputStream.read(bytes, 0, 9);
String s = new String(bytes);
System.out.println(s);
//3.关闭流
inputStream.close();
}
}
练习题目:每次只能读五个长度的字符,将文件内字符读完
public class Byte0316 {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\lo\\Desktop\\ss.txt";
FileInputStream inputStream = new FileInputStream(path);
byte[] bytes = new byte[5];
int read = 0;
while ((read = inputStream.read(bytes)) != -1){
String s = new String(bytes,0,read);
System.out.print(s);
}
System.out.println();
inputStream.close();
}
}
二、OutputStream(字节输出流基类)
1、写操作步骤
步骤1:打开字节输出流,可能会抛出FileNotFoundException异常
String path = "C:\\Users\\lo\\Desktop\\ss.txt";
FileOutputStream outputStream = new FileOutputStream(path);
写操作时,文件不存在,会自动创建文件,并写入数据
当文件目录路径不合法是则会抛出异常
步骤2:写操作,可能会抛出IOException异常
void write(int b) 每次写入一个字节
步骤3:关闭流,可能会抛出IOException异常
outputStream.close();
示例:
public static void write(){
String path = "C:\\Users\\lo\\Desktop\\ss.txt";
try {
//步骤1:打开字节输出流,可能会抛出FileNotFoundException
FileOutputStream outputStream = new FileOutputStream(path);
//步骤2:写操作,可能会抛出IOException
//写操作如果文件不存在,会自动创建文件,并写入数据
//void write(int b):每次写入一个字节
outputStream.write(97);
//void write(byte b[]):批量写入
byte[] bytes = new byte[]{'a','b','c','d','e'};
outputStream.write(bytes);
outputStream.write("hello".getBytes());
// void write(byte b[], int off, int len):批量写入,可以自定义从byte数组的起始长度和写的长度
outputStream.write(bytes,1,3); //从1号开始写三个长度
//步骤3:关闭流,可能会抛出IOException
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2、常用方法介绍
void write(int b) 每次写入一个字节
void write(byte b[]) 批量写入,写入类型为byte[]
void write(byte b[], int off, int len) 批量写入,可以自定义从byte数组的起始和读取长度
void flush() 刷新缓存