| 抽象类 | 说明 | 常用方法 |
|---|---|---|
| InputStream | 字节输入流的父类,数据单位为字节。 | • int read() • void close() |
| OutputStream | 字节输出流的父类,数据单位为字节。 | • void write(int) • void flush() • void close() |
| Reader | 字符输入流的父类,数据单位为字符。 | • int read() • void close() |
| Writer | 字符输出流的父类,数据单位为字符。 | • void write(String) • void flush() • void close() |
IO的操作步骤
- 创建源(搬那套房子)
- 选择流(选搬家公司)
- 操作(人还是卡车)
- 释放(打发搬家公司)
基础版(即一个一个的读取字符):
package com.io.cx2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* 理解操作步骤
* 1创建源
* 2选择流
* 3操作
* 4释放资源
*/
public class test1 {
public static void main(String[] args) {
//1、创建源
File src = new File("text.txt");
//2、选择流
try {
InputStream is =new FileInputStream(src);
//3、操作 (读取)
int data1 = is.read(); //第一个数据w
int data2 = is.read(); //第二个数据o
int data3 = is.read(); //第三个数据s
int data4 = is.read(); //不是数据,文件的末尾返回-1
System.out.println((char)data1);
System.out.println((char)data2);
System.out.println((char)data3);
System.out.println(data4);
//4、释放资源
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
完整的IO版如下:
package com.io.cx2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class test2 {
public static void main(String []args) {
//1.创建源
File src=new File("D:\\EclipsePlace\\IO\\src\\com\\io\\cx2\\text.txt");
//2.选择流
InputStream r=null;
try {
r=new FileInputStream(src);
//3.操作
int temp;
while((temp=r.read())!=-1) {
System.out.println((char)temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//4.释放资源
if(null!=r)
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//建议第二个代码多写几遍,这是IO的基础代码
本文深入讲解Java中的IO流概念,包括字节输入流与输出流、字符输入流与输出流的父类及其常用方法。通过两个示例代码,演示了如何使用FileInputStream进行文件读取,从创建源到选择流、操作数据直至释放资源的完整过程。
647

被折叠的 条评论
为什么被折叠?



