IO流
常用类
1流的种类
- 按方向分:输入流,输出流
- 按类型分:字节流,字符流,转换流
- 按操作方式分:节点流,过滤流
2基本使用方式
public class Test4write {
/*
* 流的读写操作
* 1,打开流
* 2,读取内容
* 3,写入内容
* 4,一定要关闭流
* */
public static void main(String[] args) {
File file = new File("E:/youxi/2.txt"); //文件读取位置
File file1 = new File("E:/youxi/1.txt");//文件写入位置
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null; //缓冲流
FileOutputStream fos = null; //文件输出流
BufferedOutputStream bos = null; //缓冲流
//io流有异常全部放在try,catch中操作
try {
//1,打开流
fis = new FileInputStream(file); //打开文件输入流
bis = new BufferedInputStream(fis); //给文件输入流套上缓冲流
fos = new FileOutputStream(file1); //打开文件输出流
bos = new BufferedOutputStream(fos); //套上缓冲流
//缓冲流可以提高效率
//2 读取文件内容
byte[] b = new byte[1024]; //将读取的数据放在字节数组中
int len = 0; //读取字节的长度
//循环读取,将文件内容读取到byte数组中,如果读取的字节大于或等于就继续读取
//没有读取到数据是会返回-1
while((len=bis.read(b, 0, b.length))>=0){ //用read带参数的方法
//3写入文件
bos.write(b, 0, b.length); //用write带参数的方法
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//最后要分别关闭流
//如果有缓冲流,直接关闭缓冲流就可以
try {
if(bis!=null) bis.close(); //关闭输入流
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bos!=null) bos.close(); //关闭输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据流和字符流的操作方式与这都差不多
3转换流
public static void main(String[] args) {
BufferedReader br = null; //字符读取缓冲流
try {
//读取标准输入流(标准输入流是字节流型的)
//所以需要使用转换流InputStreamReader
br = new BufferedReader(new InputStreamReader(System.in));//转换流的应用
//循环读取
String str = null; //存放读取的内容
while((str=br.readLine())!=null){
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//最后记得关闭流
try {
if(br!=null)br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4对象流
对象流可以存储对象,但是该对象类要实现Serializable接口
1存储的对象实现Serializable接口,如果有不需要存储的属性可以使用transient关键字
//对象一定要实现Serializable接口才能读写
class Ts implements Serializable{
int i;
String str;
//设置之后这个属性就不会被存储
transient int z;
public Ts(int i,String str) {
this.i=i;
this.str = str;
}
}
2对象流的操作
public static void main(String[] args) {
//实例化对象
Ts ts = new Ts(3, "asd");
//
File file = new File("E:/youxi/1.txt");
ObjectOutputStream oos = null; //输出流
ObjectInputStream ois = null; //输入流
try {
oos = new ObjectOutputStream(new FileOutputStream(file)); //打开流
ois = new ObjectInputStream(new FileInputStream(file));
//写入文件
oos.writeObject(ts);
//读取
Ts t = (Ts) ois.readObject();
System.out.println(t);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
if(oos!=null)oos.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
try {
if(ois!=null)ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}