Java中的File类和IO流( 二 )


这里需要注意的是,字符流只适用于文本的输入输出,对于图片,视频等二进制文件则无法使用字符流进行操作 。
7.字节流
1)字节输出流——OutputStream(所有字节输出流的父类)
字节输出流的使用,以FileOutputStream为例
public void test1() throws Exception {
//定义字节输出流对象
OutputStream osp = new FileOutputStream("D:/AAAkejian/Test/test1.txt");
String str = "Add abcd";
//将字符串转化为字节存入字节数组中
byte[] bList = str.getBytes();
//写入文件
osp.write(bList);
//刷新流
osp.flush();
//关闭流
osp.close();
}
2)字节输入流——InputStream(所有字节输入流的父类)
字节输入流的使用,以FileInputStream为例,这里的读取规则,与字符输入流类似,利用循环进行循环读取文件内容 。
public void test() throws Exception{
//创建字节输入流对象
InputStream ips = new FileInputStream("D:/AAAkejian/Test/test1.txt");
byte[] bList = new byte[3000];
int count = 0;
while( (count=ips.read(bList))!=-1 ){
//把byte数组转换为字符串
String str=new String(bList,0,count);
System.out.println(str);
}
ips.close();
}
3)利用字节输入输出流完成图片的复制功能
public void test()throws Exception{
//定义字节输入流对象
InputStream ips = new FileInputStream("D:/AAAkejian/Test/test3.png");
//定义字节输出流对象
OutputStream ops = new FileOutputStream("D:/AAAkejian/Test/test1.png");
//定义字节数组,用于存储所读取的内容
byte[] bList = new byte[100];
int count =0;
while ((count = ips.read(bList))!=-1){
ops.write(bList,0,count);
ops.flush();
}
ops.close();
ips.close();
}
8.缓存流
缓存流是在基础流(InputStream OutputStream Reader Writer)之上,添加了一个缓冲池的功能,用于提高IO效率,降低IO次数
缓冲流的使用:
public void test()throws Exception{
//定义字节输出流
OutputStream ops = new FileOutputStream("D:/AAAkejian/Test/test1.txt");
//定义缓存流对象
BufferedOutputStream bfops = new BufferedOutputStream(ops);
String str = "new content";
byte[] bList = str.getBytes();
//此时的内容在缓冲池中,并未写入文件
bfops.write(bList);
//刷新缓冲池,将缓冲池中的内容写入文件中
//bfops.flush();
//h缓存流中的close方法,会先执行flush方法
bfops.close();
}
9.对象流
对象流的意义在于数据的持久化,例如游戏存到,就是一种对象流的使用 。
在日常程序运行中,内容都是存储在内存中的,而将内存中的数据,存储到磁盘中,就实现了数据的持久化 。
1)对象流输出的使用——ObjectOutputStream--序列化(存档):
public class Role implements Serializable {
private String name;
private int level;
private String power;
public Role(String name, int level, String power) {
this.name = name;
this.level = level;
this.power = power;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getPower() {
return power;
}
public void setPower(String power) {
this.power = power;
}
}
public void test()throws Exception{
OutputStream ops = new FileOutputStream("d:/AAAkejian/Test/test3.txt");
ObjectOutputStream oops = new ObjectOutputStream(ops);
//使用对象流调用输出流的输出方法,被输出的对象的类必须实现Serializable接口
Role r1 = new Role("gjx",55,"撒泼打滚");
oops.writeObject(r1);
oops.close();
}
2)对象输入流的使用——ObjectInputStream--反序列化(读档):
public void test()throws Exception{
InputStream ips = new FileInputStream("D:/AAAkejian/Test/test3.txt");
ObjectInputStream oips = new ObjectInputStream(ips);
Object o = oips.readObject();
System.out.println(o);
oips.close();
}


【Java中的File类和IO流】


推荐阅读