IO流原理及流的分类
Java IO原理
-
I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
-
Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行。
-
java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
-
输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
-
输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中。
流的分类
-
按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)
-
按数据流的流向不同分为:输入流,输出流
-
按流的角色的不同分为:节点流,处理流
(抽象基类) | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
1.Java的IO流共涉及40多个类,实际上非常规则,都是从如下4个抽象基类派生的。
2.由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
节点流和处理流
-
节点流:直接从数据源或目的地读写数据
-
处理流:不直接连接到数据源或目的地,而是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能。
InputStream& Reader
-
InputStream和Reader 是所有输入流的基类。
-
InputStream(典型实现:FileInputStream)
-
int read()
-
int read(byte[] b)
-
int read(byte[] b, int off, int len)
-
-
Reader(典型实现:FileReader)
-
int read()
-
int read(char [] c)
-
int read(char [] c, int off, int len)
-
-
程序中打开的文件IO 资源不属于内存里的资源,垃圾回收机制无法回收该资源,所以应该显式关闭文件IO 资源。
-
FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream 用于读取非文本数据之类的原始字节流。要读取字符流,需要使用FileReader
public class FileReadWriterTest {
public static void main(String[] args) {
File file = new File("Hello.txt");
System.out.println(file.getAbsolutePath());
}
@Test
/*
将Hello下的Hello.txt文件内容读入到程序中,并输出到控制台
说明点:
1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
3. 读入的文件一定要存在,否则就会报FileNotFoundException。
*/
public void testFileReader() {
FileReader fr = null;
try {
//1. 实例化File类的对象,指明要操作的文件
File file = new File("Hello.txt");
System.out.println(file.getAbsolutePath());
//2. 提供具体的流
fr = new FileReader(file);
//3. 数据的读入
int date;
while ((date = fr.read()) != -1) {
System.out.print((char) date);
}
} catch (IOException e) {
e.printStackTrace();
}
//4.资源的关闭
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFileReader1() {
FileReader fr = null;
try {
File file = new File("Hello.txt");
fr = new FileReader(file);
char[] cbuf = new char[3];
int len;
//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
//方式一:
// while ((len = fr.read(cbuf)) != -1) {
// for (int i = 0; i < len; i++) {
// System.out.print(cbuf[i]);
// }
// }
//方式二:
while ((len = fr.read(cbuf)) != -1) {
java.lang.String str = new java.lang.String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}