IO原理
1.I/O
是
Input/Output
的缩写,
I/O
技术是非常实用的技术,用于
处理设备之间的数据传输
。如读
/
写文件,网络通讯等。
2.ava
程序中,对于数据的输入
/
输出操作以
“流(stream)”
的
方式进行。
3.java.io
包下提供了各种“流”类和接口,用以获取不同种类的
数据,并通过
标准的方法
输入或输出数据
输入
input
:
读取外部数据(磁
盘、光盘等存储设备的数据)到
程序(内存)中
输出
output
:
将程序(内存)
数据输出到磁盘、光盘等存储设
备中
IO 流体系
![](https://i-blog.csdnimg.cn/blog_migrate/56d1ec6b419996f0b689da542ff43b6c.png)
OutPutStream(字节输出流) 使用
// 文件路径
File f1 = new File("C:\\Users\\Yxb\\Desktop\\test.txt");
// 因为OutputStream是抽象类 没法实例化 通过向上转型实例化子类来使用
OutputStream out = new FileOutputStream(f1);
out.write(97);
out.close();
这样就可以写入我们想要写入的内容了。
可是现在还有一个问题,如果我们每次运行代码它都会将原本的内容替换成我们想要输入的内容,没法接着后面继续写入。这是因为它的FileOutputStream参数后面会默认是false,我们只需要改成true即可
OutputStream out = new FileOutputStream(f2,false);// (默认false)替换原本内容
OutputStream out = new FileOutputStream(f2,true);// 在原本的内容后面继续写入
InputStream(输入流) 使用:
File f1 = new File("C:\\Users\\Yxb\\Desktop\\test.txt");
InputStream in = new FileInputStream(f1);
// 如果到达流末尾而没有可用的字节,则返回值 -1
int read = in.read();
// read为ASCII码表中所对应的十进制数字,使用强制类型转换变成char类型
System.out.println((char)read);
in.close();
这样我们每次就可以读取一个字节,这样效率太慢了。因为到达流末尾而没有可用的字节,则返回值 -1,那么我们可以使用循环来打印所有内容
// 声明一个byte数组,长度随意
byte[] b = new byte[10];
// 声明一个int类型的值
int i2;
// while循环,将.read(b)的值赋值给i2,判断条件如果i2大于0则证明数组中有值,否则结束循环
while ((i2 = in.read(b)) > 0) {
// String的有参构造方法
// String s = new String(byte[] b); 将byte数组传入String的构造方法中,打印s即可
String s = new String(b,0,i2);
System.out.print(s);
}
字符输出流
import java.io.FileWriter;
import java.io.IOException;
public class filewrite {
public static void main(String[] args) throws IOException {
FileWriter fw=new FileWriter("E:\\st\\IO\\aaa\\36.txt",true);
输出字符
fw.write("你好阿彬");
输出一个字符数组
char[] chars= {'1','5','0','阿','彬'};
fw.write(chars);
fw.close();
}
}
字符输入流
import java.io.FileReader;
import java.io.IOException;
public class fileread {
public static void main(String[] args) throws IOException {
FileReader fd=new FileReader("E:\\st\\IO\\aaa\\xxxx.txt");
int a;
while ((a= fd.read())!=-1){
System.out.print((char) a);
}
fd.close();
}
}