美文网首页
java io 流 & 序列化与反序列化

java io 流 & 序列化与反序列化

作者: 帅哥_刷哥 | 来源:发表于2017-09-14 15:51 被阅读11次

1.介绍

流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。 
流是指一连串流动的字符,是以先进先出方式发送信息的通道

2.分类

根据处理数据类型的不同分为:字符流和字节流
  字节流是 8 位通用字节流,字符流是 16 位 Unicode 字符流

根据数据流向不同分为:输入流和输出流
  对输入流只能进行读操作,对输出流只能进行写操作,程序中需要根据待传输数据的不同特性而使用不同的流。
  输入输出流是相对于计算机内存来说的

3.字符流和字节流

字符流的由来: 因为数据编码的不同,而有了对字符进行高效操作的流对象。本质其实就是基于字节流读取时,去查了指定的码表。 字节流和字符流的区别:

读写单位不同:字节流以字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。
处理对象不同:字节流能处理所有类型的数据(如图片、avi等),而字符流只能处理字符类型的数据。
结论:只要是处理纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。

4.IO流框架

FileInputStream 
  不带缓冲区
  字节流基础输入流 
  不支持mark和reset
FileOutputStream 
  不带缓冲区
  字节流基础输出流 
  支持追加

BufferedInputStream
  带缓冲区
  字节输入流
  支持mark和reset
BufferedOutputStream
  带缓冲区
  字节输出流

FileReader 
  不带缓冲区
  字符流基础输入流
  不支持mark和reset
FileWriter  
  不带缓冲区
  字符流基础输出流
  支持追加

BufferedReader
  带缓冲区
  字符流输入流
  支持mark和reset
BufferedWriter
  带缓冲区
  字符流输出流

InputStreamReader
  字节流与字符流的转换流
  可以带编码
OutputStreamWriter
  字节流与字符流的转换流
  可以带编码
image.png

5.字节输出流-FileOutputStream-包含可以追加

//第一种方式- 不可以追加
public void write(){
    FileOutputStream output=null;
    try {
        File file = new File("D://test.txt");
        output = new FileOutputStream(file);
        output.write(97);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(output != null)
                output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式- 不可以追加
public void write(){
    FileOutputStream output=null;
    try {
        File file = new File("D://test.txt");
        output = new FileOutputStream(file);
        output.write("javatest".getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(output != null)
                output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式- 不可以追加
public void write(){
    FileOutputStream output=null;
    try {
        File file = new File("D://test.txt");
        output = new FileOutputStream(file);
        byte[] b = "javatest".getBytes();
        //从b数组的off位置开始写入到文件
        int off = 0;
        //一共写入多少个字符 注意:off加上len不能超出数组b的长度
        int len = b.length;
        output.write(b, off, len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(output != null)
                output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种方式 - 可以追加
public void write(){
    FileOutputStream output=null;
    try {
        File file = new File("D://test.txt");
        output = new FileOutputStream(file,true);
        byte[] b = "javatest".getBytes();
        //从b数组的off位置开始写入到文件
        int off = 0;
        //一共写入多少个字符 注意:off加上len不能超出数组b的长度
        int len = b.length;
        output.write(b, off, len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(output != null)
                output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.字节输入流-FileInputStream

//第一种写法
public void read(){
    FileInputStream input=null;
    try {
        File file = new File("D://test.txt");
        input = new FileInputStream(file);
        int num;
        while((num = input.read())!= -1){
            System.out.println((char)num);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(input != null)
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种写法
public void read(){
    FileInputStream input=null;
    try {
        File file = new File("D://test.txt");
        input = new FileInputStream(file);
        byte[] b = new byte[1024];
        //这个是从文件中读取的长度
        int num;
        while((num = input.read(b))!= -1){
            System.out.println(new String(b,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(input != null)
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种长度
public void read(){
    FileInputStream input=null;
    try {
        File file = new File("D://test.txt");
        input = new FileInputStream(file);
        byte[] b = new byte[1024];
        //这个是从文件中读取的长度
        int num;
        //b数组中的偏移量  0 表示从b数组的弟0位开始写入
        int off = 0;
        //可读取的最大长度,注意:off+len不能超出b数组的长度
        int len = b.length;
        while((num = input.read(b, off,len))!= -1){
            System.out.println(new String(b,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(input != null)
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种写法 skip
public void read(){
    FileInputStream input=null;
    try {
        File file = new File("D://test.txt");
        input = new FileInputStream(file);
        //skip 是跳跃的长度,从当前位置跳过几个长度
        long n = 3;
        input.skip(n);
        int num;
        while((num = input.read())!= -1){
            System.out.println((char)num);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(input != null)
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第五 注意
FileInputStream则没有重写父类InputStream的这两个方法,其不具有mark和reset方法的能力

//第六 
markSupported方法是查看流是否支持mark和reset的能力

7.带缓冲区的字节输出流-BufferedOutputStream

//第一种写法
public void write(){
    BufferedOutputStream boutput=null;
    try {
        File file = new File("D://test.txt");
        FileOutputStream output = new FileOutputStream(file,true);
        boutput = new BufferedOutputStream(output);
        boutput.write(97);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(boutput != null)
                boutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种写法
public void write(){
    BufferedOutputStream boutput=null;
    try {
        File file = new File("D://test.txt");
        FileOutputStream output = new FileOutputStream(file,true);
        boutput = new BufferedOutputStream(output);
        boutput.write("javatest".getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(boutput != null)
                boutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种写法
public void write(){
    BufferedOutputStream boutput=null;
    try {
        File file = new File("D://test.txt");
        FileOutputStream output = new FileOutputStream(file,true);
        boutput = new BufferedOutputStream(output);
        byte[] b = "javatest".getBytes();
        //b数组的开始下标
        int off = 0;
        //要写出的长度:注意:off+len 不能大于b的长度
        int len = b.length;
        boutput.write(b,off,len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(boutput != null)
                boutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种写法  flush的用法
public void write(){
    BufferedOutputStream boutput=null;
    try {
        File file = new File("D://test.txt");
        FileOutputStream output = new FileOutputStream(file,true);
        boutput = new BufferedOutputStream(output);
        byte[] b = "javatest".getBytes();
        //b数组的开始下标
        int off = 0;
        //要写出的长度:注意:off+len 不能大于b的长度
        int len = b.length;
        boutput.write(b,off,len);
        //在缓冲区没有满并且流没有关闭的情况下,需要手动调用flush,把缓冲区的内容刷入文件
        //只要记得关闭流,flush就可以不用写
        boutput.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
//        try {
//            if(boutput != null)
                //close()时会自动flush
//              boutput.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

8.带缓冲区的字节输入流-BufferedInputStream

//第一种方式
public void read(){
    BufferedInputStream binput = null;
    try {
        File file = new File("D://test.txt");
        FileInputStream input = new FileInputStream(file);
        binput = new BufferedInputStream(input);
        int num;
        while((num = binput.read()) != -1){
            System.out.println((char)num);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(binput != null)
                binput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式
  public void read(){
    BufferedInputStream binput = null;
    try {
        File file = new File("D://test.txt");
        FileInputStream input = new FileInputStream(file);
        binput = new BufferedInputStream(input);
        byte[] b = new byte[1024];
        //读取的长度
        int num;
        while((num = binput.read(b)) != -1){
            System.out.println(new String(b,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(binput != null)
                binput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式
public void read(){
    BufferedInputStream binput = null;
    try {
        File file = new File("D://test.txt");
        FileInputStream input = new FileInputStream(file);
        binput = new BufferedInputStream(input);
        byte[] b = new byte[1024];
        //读取的长度
        int num;
        int off = 0;
        int len = b.length;
        while((num = binput.read(b,off,len)) != -1){
            System.out.println(new String(b,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(binput != null)
                binput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种方式 - skip
public void read(){
    BufferedInputStream binput = null;
    try {
        File file = new File("D://test.txt");
        FileInputStream input = new FileInputStream(file);
        binput = new BufferedInputStream(input);
        long n = 3;
        binput.skip(n);
        byte[] b = new byte[1024];
        //读取的长度
        int num;
        int off = 0;
        int len = b.length;
        while((num = binput.read(b,off,len)) != -1){
            System.out.println(new String(b,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(binput != null)
                binput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第五  markSupported
markSupported 方法测试是否支持mark和reset方法

//第六  mark与reset
public void read(){
    BufferedInputStream binput = null;
    try {
        File file = new File("D://test.txt");
        FileInputStream input = new FileInputStream(file);
        binput = new BufferedInputStream(input);
        if(!binput.markSupported()){
            System.out.println("不支持 mark");
            return;
        }
        //标记一个位置,在哪里mark 就标记哪里,标记当前位置
        binput.mark(1);
        int num = binput.read();
        System.out.println((char)num);
        num = binput.read();
        System.out.println((char)num);
        //第二次读取跟第一次读取结果一样。因为只读了一个,没有超过mark设置的整数。所以mark有效
        binput.reset();
        num = binput.read();
        System.out.println((char)num);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(binput != null)
                binput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

9.字符流 - FileReader

//第一种方式
public void read(){
    FileReader reader = null;
    try {
        File file = new File("D:\\test.txt");
        reader = new FileReader(file);
        int num;
        while((num = reader.read())!= -1){
            System.out.println((char)num);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式
public void read(){
    FileReader reader = null;
    try {
        File file = new File("D:\\test.txt");
        reader = new FileReader(file);
        char[] b = new char[1024];
        int num;
        while((num = reader.read(b))!= -1){
            System.out.println(new String(b,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式
public void read(){
    FileReader reader = null;
    try {
        File file = new File("D:\\test.txt");
        reader = new FileReader(file);
        char[] b = new char[1024];
        int offset=0;
        //注意:offset + length 不能超出 b数组的长度
        int length = b.length;
        int num;
        while((num = reader.read(b,offset,length))!= -1){
            System.out.println(new String(b,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种写法
public void read(){
    FileReader reader = null;
    try {
        File file = new File("D:\\test.txt");
        reader = new FileReader(file);
        //capacity是该缓冲区中读取字符
        int capacity = 12;
        CharBuffer target = CharBuffer.allocate(capacity);
        int num ;
        while((num = reader.read(target))!= -1){
            //把缓冲区的内容移出
            target.flip();
            System.out.println(target.toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第五 getEncoding 获取输入流编码
String encoding = reader.getEncoding();

//第六  skip 跳跃字符数
long n = 2;
reader.skip(n);

//第七 markSupported 是否支持mark和reset
不支持mark和reset

//第八 ready 流是否就绪

10.字符流 - FileWriter

//第一种方式
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        writer.write(97);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        char[] cbuf = new char[]{'j','a','v','a','t','e','s','t'};
        writer.write(cbuf);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        char[] cbuf = new char[]{'j','a','v','a','t','e','s','t'};
        int off=0;
        int len=cbuf.length;
        writer.write(cbuf,off,len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种方式
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        writer.write("javatest");
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第五种方式
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        String str = "javatest";
        int off = 0;
        int len = str.length();
        writer.write(str, off, len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第六种
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        String str = "javatest";
        writer.append('a');
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第七种
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        writer.append("test");
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第八种
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file);
        String str = "javatest";
        int start = 0;
        int end = str.length();
        writer.append(str,start,end);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第九种 - 支持追加
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file,true);
        String str = "javatest";
        int start = 0;
        int end = str.length();
        writer.append(str,start,end);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第十种方式
public void write(){
    FileWriter writer = null;
    try {
        File file = new File("D:\\test.txt");
        writer = new FileWriter(file,true);
        writer.write("javatest");
        //再没有close的时候,要调用flush才能刷出缓冲区
        writer.flush();
        
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
//      try {
//          if(writer != null){
//              //close时会默认flush
//              writer.close();
//          }
//      } catch (IOException e) {
//          e.printStackTrace();
//      }
    }
}


//第十一 getEncoding获取文本的编码
String encoding = writer.getEncoding();

11.带缓冲区的字符输入流 BufferedReader

//第一种方式
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileReader writer = new FileReader(file);
        breader = new BufferedReader(writer);
        int num;
        while((num = breader.read())!=-1){
            System.out.println((char)num);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null){
                breader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileReader writer = new FileReader(file);
        breader = new BufferedReader(writer);
        char[] cbuf = new char[1024];
        int num;
        while((num = breader.read(cbuf))!=-1){
            System.out.println(new String(cbuf,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null){
                breader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileReader writer = new FileReader(file);
        breader = new BufferedReader(writer);
        char[] cbuf = new char[1024];
        int num;
        int off = 0;
        int len = cbuf.length;
        while((num = breader.read(cbuf,off,len))!=-1){
            System.out.println(new String(cbuf,0,num));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null){
                breader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种方式
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileReader writer = new FileReader(file);
        breader = new BufferedReader(writer);
        int capacity = 12;
        CharBuffer target = CharBuffer.allocate(capacity);
        int num;
        while((num = breader.read(target))!=-1){
            target.flip();
            System.out.println(target.toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null){
                breader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第五种方式
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileReader writer = new FileReader(file);
        breader = new BufferedReader(writer);
        String str;
        while((str = breader.readLine())!=null){
            System.out.println(str);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null){
                breader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第六 ready 流是否已经准备好
  boolean ready = breader.ready();

//第七 skip 跳跃多少个字符
  long n = 3;
  breader.skip(n);

//第八 markSupported 是否支持mark和reset
  boolean markSupported = breader.markSupported();

//第九 mark和reset
public void read(){
    BufferedReader breader = null;
    try {
        /*
         * javatest
         * test
         * 文件中最少要两行
         * */
        File file = new File("D:\\test.txt");
        FileReader writer = new FileReader(file);
        breader = new BufferedReader(writer);
        breader.mark(1);
        String str = breader.readLine();
        System.out.println(str);
        breader.reset();
        str = breader.readLine();
        System.out.println(str);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null){
                breader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第十 获得文件总行数
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileReader writer = new FileReader(file);
        breader = new BufferedReader(writer);
        //获得文件总行数
        Stream<String> lines = breader.lines();
        System.out.println(lines.count());
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null){
                breader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

12.带缓冲区的字符输出流 BufferedWriter

//第一种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        bwriter.write(97);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        char[] cbuf = new char[]{'j','a','v','a','t','e','s','t'};
        bwriter.write(cbuf);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        char[] cbuf = new char[]{'j','a','v','a','t','e','s','t'};
        int off = 0;
        int len = cbuf.length;
        bwriter.write(cbuf,off,len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        bwriter.write("javatest");
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第五种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        String str = "javatest";
        int off = 0;
        int len = str.length();
        bwriter.write(str,off,len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//第六种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        bwriter.append('a');
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第七种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        bwriter.append("javatest");
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第八种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        String str = "javatest";
        int start = 0;
        int end = str.length();
        bwriter.append(str,start,end);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第九种 writeLine 
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        //
        bwriter.newLine();
        bwriter.write("javatest");
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null){
                //close时会默认flush
                bwriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第十种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileWriter writer = new FileWriter(file,true);
        bwriter = new BufferedWriter(writer);
        bwriter.write("javatest");
        //在没有关闭流的情况下,需要flush
        bwriter.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
//      try {
//          if(bwriter != null){
//              //close时会默认flush
//              bwriter.close();
//          }
//      } catch (IOException e) {
//          e.printStackTrace();
//      }
    }
}

13.字节流与字符流之间的转换 - 输入流

//第一种方式
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis);
        breader = new BufferedReader(isr);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null)
                breader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式 - 增加编码
public void read(){
    BufferedReader breader = null;
    try {
        File file = new File("D:\\test.txt");
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        breader = new BufferedReader(isr);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(breader != null)
                breader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

14.字节流与字符流之间的转换 - 输出流

//第一种方式
public void write(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        bwriter = new BufferedWriter(osw);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null)
                bwriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式 - 增加编码
public void read(){
    BufferedWriter bwriter = null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
        bwriter = new BufferedWriter(osw);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(bwriter != null)
                bwriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

15.序列化与反序列化

序列化是将对象的状态存储到特定存储介质中的过程
反序列化则是从特定存储介质中的数据重新构建对象的过程 
image.png

16.基本数据类型和对象输出流 - ObjectOutputStream

//第一种方式
import java.io.Serializable;
public class Student implements Serializable{
    private static final long serialVersionUID = 8509905684212538380L;
    private int id;
    private String name;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
public void write(){
    ObjectOutputStream ooutput=null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream output = new FileOutputStream(file);
        ooutput = new ObjectOutputStream(output);
        Student student = new Student();
        student.setId(1);
        student.setName("张三");
        student.setAge(20);
        ooutput.writeObject(student);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(ooutput != null)
                ooutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式
public void write(){
    ObjectOutputStream ooutput=null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream output = new FileOutputStream(file);
        ooutput = new ObjectOutputStream(output);
        Student student = new Student();
        student.setId(1);
        student.setName("张三");
        student.setAge(20);
        ooutput.writeUnshared(student);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(ooutput != null)
                ooutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式
public void write(){
    ObjectOutputStream ooutput=null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream output = new FileOutputStream(file);
        ooutput = new ObjectOutputStream(output);
        ooutput.writeByte(1);
        ooutput.writeShort(2);
        ooutput.writeInt(3);
        ooutput.writeLong(4l);
        ooutput.writeFloat(20.0f);
        ooutput.writeDouble(20.0);
        ooutput.writeBoolean(true);
        ooutput.writeChar('a');
        ooutput.writeUTF("zhangsan");
        ooutput.writeBytes("lisi");
        ooutput.write(97);
        ooutput.write("wangwu".getBytes());
        ooutput.writeChars("zhaoliu");
        byte[] buf = new byte[]{1,2,3,4};
        int off = 0;
        int len = buf.length;
        ooutput.write(buf, off, len);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(ooutput != null)
                ooutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种方式
public void write(){
    ObjectOutputStream ooutput=null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream output = new FileOutputStream(file);
        ooutput = new ObjectOutputStream(output);
        ooutput.writeByte(1);
        ooutput.writeShort(2);
        ooutput.writeInt(3);
        ooutput.writeLong(4l);
        ooutput.writeFloat(20.0f);
        ooutput.writeDouble(20.0);
        ooutput.writeBoolean(true);
        ooutput.writeChar('a');
        ooutput.writeUTF("zhangsan");
        ooutput.writeBytes("lisi");
        ooutput.write(97);
        ooutput.write("wangwu".getBytes());
        ooutput.writeChars("zhaoliu");
        byte[] buf = new byte[]{1,2,3,4};
        int off = 0;
        int len = buf.length;
        ooutput.write(buf, off, len);
        //在没有关闭流的情况下 刷出数据
        ooutput.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
//      try {
//          if(ooutput != null)
//              ooutput.close();
//      } catch (IOException e) {
//          e.printStackTrace();
//      }
    }
}

//第五种方式
public void write(){
    ObjectOutputStream ooutput=null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream output = new FileOutputStream(file);
        ooutput = new ObjectOutputStream(output);
        PutField putFields = ooutput.putFields();
        putFields.put("name", "张三");
        ooutput.writeFields();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(ooutput != null)
                ooutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

17.基本数据类型和对象输入流 - ObjectInputStream

//第一种方式
public void read(){
    ObjectInputStream oinput=null;
    try {
        File file = new File("D:\\test.txt");
        FileInputStream input = new FileInputStream(file);
        oinput = new ObjectInputStream(input);
        Student student = (Student)oinput.readObject();
        System.out.println(student);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(oinput != null)
                oinput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第二种方式
public void read(){
    ObjectInputStream oinput = null;
    try {
        File file = new File("D:\\test.txt");
        FileInputStream input = new FileInputStream(file);
        oinput = new ObjectInputStream(input);
        Student student = (Student)oinput.readUnshared();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(oinput != null)
                oinput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第三种方式
public void read(){
    ObjectInputStream oinput = null;
    try {
        File file = new File("D:\\test.txt");
        FileInputStream input = new FileInputStream(file);
        oinput = new ObjectInputStream(input);
        int read = oinput.read();
        byte bytenum = oinput.readByte();
        short shortnum = oinput.readShort();
        int intnum = oinput.readInt();
        long longnum = oinput.readLong();
        float floatnum = oinput.readFloat();
        double doublenum = oinput.readDouble();
        char charnum = oinput.readChar();
        boolean booleannum = oinput.readBoolean();
        String readUTF = oinput.readUTF();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(oinput != null)
                oinput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//第四种方式
public void read(){
    ObjectInputStream oinput = null;
    try {
        File file = new File("D:\\test.txt");
        FileInputStream input = new FileInputStream(file);
        oinput = new ObjectInputStream(input);
        GetField readFields = oinput.readFields();
        boolean b = readFields.get("name",false);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(oinput != null)
                oinput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

18.二进制输入流 - DataInputStream

public void read(){
    DataInputStream dinput = null;
    try{
        File file = new File("D:\\test.txt");
        FileInputStream input = new FileInputStream(file);
        dinput = new DataInputStream(input);
        byte readByte = dinput.readByte();
        short readShort = dinput.readShort();
        int readInt = dinput.readInt();
        long readLong = dinput.readLong();
        float readFloat = dinput.readFloat();
        double readDouble = dinput.readDouble();
        char readChar = dinput.readChar();
        boolean readBoolean = dinput.readBoolean();
        String readUTF = dinput.readUTF();
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        try {
            if(dinput != null)
                dinput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

19.二进制输出流 - DataOutputStream

public void write(){
    DataOutputStream doutput = null;
    try {
        File file = new File("D:\\test.txt");
        FileOutputStream out = new FileOutputStream(file);
        doutput = new DataOutputStream(out);
        doutput.writeByte(1);
        doutput.writeShort(2);
        doutput.writeInt(3);
        doutput.writeLong(4l);
        doutput.writeFloat(5.0f);
        doutput.writeDouble(6.0);
        doutput.writeChar('a');
        doutput.writeBoolean(true);
        doutput.writeUTF("zhangsan");
        doutput.writeBytes("lisi");
        doutput.writeChars("wangwu");
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(doutput != null)
                doutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

20.复制


21.剪切


相关文章

网友评论

      本文标题:java io 流 & 序列化与反序列化

      本文链接:https://www.haomeiwen.com/subject/avursxtx.html