字节输入/输出流的相关整理

字节输入流,继承自InputStream,用于输入数据,单位为字节

字节输入流结构(深色为节点流,浅色为处理流)


字节输出流是继承于OutputStream类,输出以字节为单位

字节输出流结构(深色为节点流,浅色为处理流)


FileInputStream用指定文件创建文件字节输入流:

public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("E:\\a.txt");
int read;
byte[] bytes = new byte[1024];
// 读取文件,存入字节数组b,返回读取到的字符数,存入read,默认每次将b数组装满
read = fis.read(bytes);
while (read != -1) {
read = fis.read(bytes);

         }
System.out.println(new String(bytes));
fis.close();
} catch (IOException e) {
      e.printStackTrace();
}
}

FileOutputStream创建文件字节输出流:

public static void main(String[] args) {
File file = new File("E:\\a.txt");  
        FileOutputStream fos = null;  
        try {  
            fos = new FileOutputStream(file); 
            String str = "创建文件输出字节流!!!";
            byte[] buffer = str.getBytes(); 
            fos.write(buffer);
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  finally{
        try {
        if(fos != null){
              fos.close();
                 }
} catch (IOException e) {
       e.printStackTrace();
}
         }
}


首先先了解一个接口:java.io.serializable

JAVA允许我们在内存中创建可重复使用的对象,但是,他们的生命仅仅只和虚拟机运行时间一样长。

一旦JVM停止运行,对象随之被清除,如何才能我们的对象永久保存?

java.io.Serializable接口可以使我们的对象永久的持久化

1.java.io.Serializable 接口没有任何方法属性域,实现它的类只是从语义上表明自己是可以序列化
2.在对一个 Serializable (可序列化)对象进行重新装配的过程中,不会调用任何 (甚至默认 构造器 )。整个对象都是通过从 InputStream 中取得数据恢复
3.如是要一个类是可序列化的,那么它的子类也是可序列化
4.被 transient 修饰的数据不能序

对象字节流(ObjectInputStream\ObjectOutputStream


public static void main(String[] args) {
        ObjectOutputStream oos = null;   
        FileOutputStream fos = null;   
        try {   
            fos = new FileOutputStream(new File("E:\\test.dat"));   
            oos = new ObjectOutputStream(fos);   
            oos.writeObject(new Person("jim",23));   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            if (oos != null) {   
                try {   
                    oos.close();   
                } catch (IOException e1) { e1.printStackTrace();   }   
            }   
            if (fos != null) {   
                try {   
                    fos.close();   
                } catch (IOException e2) { e2.printStackTrace();   }   
            }   
        }   
 }
对象输出流代码就差不多同上,此处略去。。。。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值