IO流
在学习IO流之前,我们首先了解一下File
File
File即文件或文件夹路径对象 ,其示例类可以是存在路径也可以是未创造路径
File有什么用
用于创建或操作文件或文件夹
File常用API
API部分看得懂会查会用即可





IO流
IO(Input 读数据 Output写数据)流即输入输出流 ,是程序 (IO操作以程序为参考对象)对文件内容进行读取或储存的方法
Input: 文件=>程序,故为读
Output: 程序=>文件,故为写(存)
IO流分类

字节流
以字节为读写最小单位 ,可以操作所有文件
FileInputStream
文件字节输入流 ,可以将文件中数据输入(读入)到程序中

代码示例
java
public class Io {
public static void main(String[] args) throws IOException {
//创建FileInputStream对象并指定操作文件路径
FileInputStream fis=new FileInputStream("D://test.txt");
//循环读取数据
int data=0;
while((data=fis.read())!=-1){
System.out.println((char)data);
}
//关闭资源
fis.close();
}
}

FileOutputStream
文件字节输出流 ,可以将数据写入指定文件中


代码示例
java
public class Io {
public static void main(String[] args) throws IOException {
//创建FileOutputStream流对象并指定路径与书写方式(续写或清除重写)
FileOutputStream fos = new FileOutputStream("D://test.txt",true); //true表示续写
//数据获取
byte[] data="I Love My Mother".getBytes();
//写入数据
fos.write(data,0,data.length);
//关闭资源
fos.close();
}
}
拷贝文件(快速读)
java
public class Io {
public static void main(String[] args) throws IOException {
//获取文件io流
FileInputStream fis=new FileInputStream("D://test.txt");
FileOutputStream fos=new FileOutputStream("D://testcopy.txt");
//开始拷贝
int flat=0;
byte[] data=new byte[1024]; //定义一次性读取大小,这里是1024字节,即1KB
while((flat=fis.read(data))!=-1){ //读数据
fos.write(data,0,data.length); //写入数据
}
//关闭资源,后用先关
fos.close();
fis.close();
}
}

字符流
................