文件与流,还有序列化与反序列化

文件

	    public static void main(String[] args) {
    File f = new File("e:/file/text/cty.txt");
    if(!f.getParentFile().exists()){
        f.getParentFile().mkdirs();
    }
    try {
        f.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

getparentfile()获取上级目录
exists()判断是否存在
mkdirs()创建这个抽象父类目录
createNewFile()是创建这个文件

io流

io流分为字符流与字节流,其中字节流的性能不如字符流。
比较明显的标志是字节流一般都是以stream结尾。

字节流

文件字节流
	fileinputstream()把文件中的数据读入流中,读取的时候最好时候缓冲数组,
									提高读写性能,减少读取次数。读取使用read()方法
	fileoutputstream()将流中的数据写出,写出使用write()方法

对象字节流
	
	对象输出流和对象输入流可以为应用提供对象持久化的功能,
	分别调用文件输出流和文件输入流来实现。

抽象字节流
	
	instream,system.ln是其输入流的主要方式
	outstream  system.out 是其主要输出方式

字符流

这是通过filewrite写入文件,然后通过fileread读取。
filewriter
filereader
在write后,要flush数据缓冲区。
字符流有一个数据缓冲区,必须要写flush,(立即刷新)。不写数据写入不了。
然后常规read

随机读写流

既可以读又可以写
RandomAccessFile() r是只读, rw是写入

序列化与反序列化

序列化是使用objectoutputstream,以及通过 fileoutputstream创建
序列化的对象必须实现serizalizable接口
通过objectwrite写入,
写完需要用flush刷新缓存区
然后close ,close是先刷新一次缓存区,然后关闭。
	
	public class XuLieHua {

 public static void main(String[] args)  {
    try {
        File f = new File("e:/file/text/xuliehua.txt");
        //序列化.
        FileOutputStream fs=new FileOutputStream(f);
        ObjectOutputStream ob= new ObjectOutputStream(fs);

        Student s=new Student("cty",18,"eat");
        ob.writeObject(s);
        ob.flush();
        ob.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


    try {
        //反序列化
        FileInputStream fi=new FileInputStream("e:/file/text/xuliehua.txt");
        ObjectInputStream oos=new ObjectInputStream(fi);

        Student s=(Student)oos.readObject();

        System.out.println(s.getName()+"------"+s.getNum()+"------"+s.getLove());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }


 }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值