一.IO流原理
- I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
输入:读取外部数据(磁盘,光盘等存储设备的数据)到程序(内存)中。
输出:将程序(内存)数据输出到磁盘,光盘等存储设备中。
- java程序中,对于数据的输入/输出操作以“流”的方式进行。
- java.io包下提供了各种“流”类和接口。用以获取不同种类的数据,并通过标准的方法输入或输出数据。
1.流的分类
- 按操作数据单位不同分为:字节流,字符流
- 按数据流的流向不同分为:输入流,输出流
- 按流的角色不同分为:节点流(直接作用在文件上),处理流(在流的基础上又包了一层,外面包的叫处理流)
2.流的体系结构
抽象基类:InputStream OutputStream Reader Writer
节点流(文件流):FileInputStream FileOutputStream FileReader FileWriter
缓冲流(处理流的一种):BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
二.字符流
read():返回读入的一个字符,如果达到文件末尾,返回-1
read(char[] cbuf):返回每次读入cbuf数组中的字符的个数
异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally
读入的文件一定要存在,否则报FileNotFoundException
读入:读取外部数据(磁盘,光盘等存储设备的数据)到程序(内存)中。
//将文件里的内容输出到控制台
public static void main(String[] args){
FileReader fr = null;
try {
//1.实例化file对象,指明要操作的文件
File file = new File("C:/Users/smallBottle/Desktop/sss.txt");//相较于当前工程
System.out.println(file.getAbsolutePath());
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
int data = fr.read();//read():空参,返回读入的一个字符,如果达到文件末尾,返回-1
while (data != -1){
System.out.println((char)data);
data = fr.read();
}
}catch (Exception e){
e.printStackTrace();
}finally {
//4.流的关闭操作
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void io() throws IOException{
//使用read()的重载方法
//1.File类的实例化
File file = new File("C:/Users/smallBottle/Desktop/sss.txt");
//2.FileReader流的实例化
FileReader fr1 = new FileReader(file);
//3.读入的操作 read(char[] cbuf):返回每次读入cbuf数组中的字符的个数
char[] cbuf = new char[5];
int len;
while( (len = fr1.read(cbuf)) != -1){
for (int i = 0; i<len;i++){
System.out.println(cbuf[i]);
}
}
//方式二:
String str = new String(cbuf,0,len);
System.out.println(str);
//4.资源的关闭
fr1.close();
}
写出:从内存中写出数据到硬盘的文件里
//1.提供File类的对象,指明写出到的文件
File file = new File("C:/Users/smallBottle/Desktop/sss.txt");
//2.提供FileWriter的对象,用于数据的写出
FileWriter fw = new FileWriter(file,false);//文件不存在自动创建,true在文件原有基础上追加,,false替换原有的文件
//3.写出的操作
fw.write("I have adrem");
//4.流资源的关闭
fw.close();
三.字节流
读入数据:
public static void io4(){
//1.造文件
File file = new File("C://Users//smallBottle//Desktop/111.png");
//2.造流
FileInputStream fis = new FileInputStream(file);
//3.读数据
byte[] buffer = new byte[5];
int len;
while (len = fis.read(buffer) != -1){
String str = new String(buffer,0,len);
System.out.println(str);
}
//4.关流
fis.close();
}
写出数据:
public static void io4(){
//1.造文件
File file = new File("C://Users//smallBottle//Desktop/111.png");
File file1 = new File("C://Users//smallBottle//Desktop/112.png");
//2.造流
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file1);
//3.读数据,复制图片
byte[] buffer = new byte[5];
int len;
while (len = fis.read(buffer) != -1){
fos.write(buffer,0,len);
}
//4.关流
fis.close();
fos.close();
}
指定路径下文件的复制:
public void stream(){
String srcPath = "";
String destPath = "";
copyFile(srcPath,destPath);
}