1. 输入流
1.1 InputStream(字节输入流)
1.1.1 FileInputStream
1.1.2 BufferedInputStream
1.1.3 ObjectInputStream
1.2 Reader(字符输入流)
1.2.1 FileReader
1.2.2 BufferedReader
1.2.3 InputStreamReader
2. 输出流
2.1 OutputStream(字节输出流)
2.1.1 FileOutputStream
2.1.2 BufferedOutputStream
2.1.3 ObjectOutputStream
2.2 Writer(字符输出流)
2.2.1 FileWriter
2.2.2 BufferedWriter
2.2.3 OutputStreamWriter
输入/输出流操作文件3步走:
1.确定要操作的文件路径
2.根据上一步的文件路径,创建输入/输出流对象
3.根据创建的对象,进行读取/写入操作
一、FileInputStream 文件输入
1、单个字节读取文件
public void readFile01(){
//文件路径
String filePath = "d:\\hello.txt";
//用于接收单个字节
int readData = 0;
//初始化FileInputStream,首先置为空
FileInputStream fileInputStream = null;
try {
//创建FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据,如果没有输入可用,此方法将被阻止
//如果返回-1,表示读取完毕
while((readData = fileInputStream.read()) != -1){
System.out.print((char) readData);//转成char显示
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、使用 read(byte[] b) 进行优化
public void readFile02(){
//文件路径
String filePath = "d:\\hello.txt";
//首先定义一个字节数组
byte[] buf = new byte[8]; //一次性读取8个字节
//读取长度
int readLength = 0;
//初始化FileInputStream ,置为空
FileInputStream fileInputStream = null;
try {
//创建FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取最多b.length字节的数据到字节数组。如果没有输入可用,此方法将被阻止
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while((readLength = fileInputStream.read(buf)) != -1){
System.out.print(new String(buf , 0 , readLength));//显示
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、输出流
1、创建方式:
(1)new FileOutputStream(filePath) 的创建方式,当写入内容是会覆盖原来的内容
(2)new FileOutputStream(filePath,true) 的创建方式,当写入内容是,追加到到文件的尾部,不会覆盖
2、代码示例:
public void writeFile(){
//创建FileOutputStream 对象
String filePath = "d:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
//得到FileOutputStream 对象
fileOutputStream = new FileOutputStream(filePath);
//写入一个字节
fileOutputStream.write('H');//char 和 int 之间可以自动转换
//写入字符串
String str = "hello,world";
//str.getBytes() 可以把 字符串 -> 字节数组
fileOutputStream.write(str.getBytes());
//write(byte[] b,int off,int len) ,将len 字节从位于偏移量off指定字节数组写入
fileOutputStream.write(str.getBytes(),0,str.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
三:字符流
方法 功能
new FilleReader(File/String) 创建对象
read( ) 每次读取单个字节,返回该字符,如果到文件末尾返回-1
read( char[] ) 批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾,则返回-1
new String( char[] ) 将 char[ ] 转换成String
new String(char[] , off, len) 将 char[] 的指定部分转换成String