栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java中IO流的介绍和使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中IO流的介绍和使用

文章目录
  • 一、IO简介*
    • 1、什么是IO
    • 2、什么是数据源(Data Source)
    • 3、什么是流
    • 4、java中四大IO抽象类
    • 5、java中流的概念细分
    • 6、java中IO流类的体系
  • 二、IO流入门案例*
  • 三、File类的使用
    • 1、File简介
    • 2、File操作方法:
  • 四、常用流对象
    • 1、文件字节流(节点流)
      • 1、1文件字节输入流
      • 1、2文件字节输出流
      • 1、3通过缓冲区提高读写效率
      • 1、4通过字节缓冲流提高读写效率
      • 1、5定义文件拷贝工具类
    • 2、文件字符流(节点流)
      • 2、1文件字符输入流
      • 2、2文件字符输出流
      • 2、3使用字符流拷贝文本文件
    • 3、字符缓冲流(处理流)
      • 3、1字符输入缓冲流
      • 3、2字符输出缓冲流
      • 3、3定义文本拷贝工具类
    • 4、转换流(处理流)
      • 4、1键盘输入,屏幕输出
    • 5、字符输出流(处理流)
    • 6、字节数组流(节点流)
      • 6、1字节数组输入流
      • 6、2字节数组输出流
    • 7、数据流(处理流)
      • 7、1数据输出流
      • 7、2数据输入流
    • 8、对象流
      • 8、1java对象的序列号和反序列化
        • 8、1、1序列化和反序列化是什么
        • 8、1、2序列化涉及的类和接口
      • 8、2操作基本数据类型
      • 8、3操作对象
        • 8、3、1将对象序列化到文件
        • 8、3、2将对象反序列化到内存
    • 9、随机访问流
    • 10、FIle类在IO中的使用
  • 五、ApacFileReaderhe IO包
    • 1、简介
    • 2、下载和添加包
    • 3、FileUtils使用示例
    • 4、IOUtils使用示例

一、IO简介* 1、什么是IO
  • I就是Input,指程序读取外部系统数据的过程
  • O就是Output,指程序将数据输出给外部系统的过程
2、什么是数据源(Data Source)
  • 数据源(Data Source)是提供数据的原始媒介,分为为程序提供数据的源设备(一般对应输入流)和接收程序数据的目标设备(一般对应输出流)。
  • 常见数据源有:数据库、文件、其他程序、网络、内存、IO设备。
3、什么是流

流是一个相对抽象的概念,所谓流就是一个传输数据的通道,这个通道可以传输相应类型的数据。进而完成数据的传输。流又分为输入流和输出流。

输入流:将数据源的数据通过输入流传输到程序中。(数据源–>程序)

输出流:将程序中的数据通过输出流传输到目的数据源中。(程序–>目的地)

4、java中四大IO抽象类
  • InputSteam:字节输入流的所有类的父类,继承自该流的流都是用于向程序中输入数据,单位为字节
    • 常用方法:
    • int read() 读取一个字节的数据,并返回int值,值大小为0-255,返回-1则表示未读出字节
    • void close() 关闭输入流对象
  • OutputSteam:字节输出流的所有类的父类,继承自该流的流都是用于程序中输出数据,单位为字节
    • 常用方法:
    • void write(int n) 向目的地中写入一个字节
    • void close() 关闭输出流对象
  • Reader:用于读取的字符流抽象类
    • 常用方法:
    • int read() 读取一个字符的数据,并返回int值,值大小为0-65535,返回-1则表示未读出字符
    • void close() 关闭输入流对象
  • Writer:用于输出的字符流抽象类
    • 常用方法:
    • void write(int n) 向目的地中写入一个字符
    • void close() 关闭输出流对象
5、java中流的概念细分
  • 按流方向分类:
    • 输入流:数据源–>程序,以InputSteam或Reader结尾
    • 输出流:程序–>目的地,以OutputSteam或Writer结尾
  • 按处理的数据分类:
    • 字节流:处理的数据为字节,以Steam结尾
    • 字符流:处理的数据为字符,以Reader或Writer结尾
  • 按处理的对象分类:
    • 节点流:直接从数据源或目的地读写数据,如FileInputSteam,DataInputSteam
    • 处理流(也叫包装流):不直接连接数据源或目的地,而是连接其他流,是处理其他流的流,用于提高程序性能,如BufferedInputSteam,BufferedReader
6、java中IO流类的体系
分类字节输入流字节输出流字符输入流字符输出流
抽象基类InputStreamOutputStreamReaderWriter
访问文件FileInputStreamFileOutputStreamFileReaderFileWriter
访问数组ByteArrayInputStreamByteArrayOutputStreamCharArrayReaderCharArrayWriter
访问管道PipedInputStreamPipedOutputStreamPipedReaderPipedWriter
缓冲流BufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriter
转换流InputStreamReaderOutputStreamWriter
对象流ObjectInputStreamObjectOutputStream
抽象基类FilterInputStreamFilterOutputStreamFilterReaderFilterWriter
打印流PrintStreamPrintWriter
特殊流DataInputStreamDataOutputStream
流对象作用
InputStream/OutputStream字节流的抽象类。
Reader/Writer字符流的抽象类。
FilelnputStream/FileoytputStream节点流:以字节为单位直接操作“文件”。
ByteArrayInputStream/ByteArrayOutputStream节点流:以字节为单位直接操作“字节数组对
ObjectInputStream/ObjectOutputStream处理流:以字节为单位直接操作“对象”。
DatalnputStream/DataOutputStream处理流:以字节为单位直接操作“基本数据类型与字符串类型”。
FileReader/FileWriter节点流:以字符为单位直接操作“文本文件”(注意:只能读写文本文件)。
BufferedReader/BufferedWriter处理流:将Reader/Writer对象进行包装,增加缓存功能,提高读写效率。
BufferedInputStream/BufferedOutputStream处理流:将lnputStream/OutputStream对象进行包装,增加缓存功能,提高读写效率。
InputStreamReader/OutputStreamWriter处理流:将字节流对象转化成字符流对象。
PrintStream处理流:将OutputStream进行包装,啊以方便地输出字符,更加灵活。
二、IO流入门案例*
FileInputStream in = null;//新建一个FileInputStream流对象
try {
    in = new FileInputStream("c:\Users\86131\Desktop\JavaSE\code\Hello.txt");
    StringBuilder stringBuilder = new StringBuilder();
    int s = 0;
    while( (s = in.read())!=-1){//如果读取错误,及读取完毕,则返回-1,因此如果返回-1则结束循环
        System.out.print((char) s);//将读取到的int型转化成char型输出
        //将读取到的字符s转化成char型并添加到字符串stringBuilder中
        stringBuilder.append((char)s);
    }
    System.out.println(" ");
    System.out.println(stringBuilder);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (in != null) {
        try {
            in.close();//关闭IO流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
三、File类的使用 1、File简介
  • “File类源于java.io.File包,是文件和目录路径名的抽象表示,主要用于文件和目录的创建、查找和删除等操作。”
  • 一个File对象可以代表一个文件或目录。
2、File操作方法:
  • 文件:

    //创建一个新file对象,括号内参数为路径;创建对象并不会在路径处创建文件
    File file = new File("C:\Users\86131\Desktop\JavaSE\IO测试\Demo01.txt");
    System.out.println(file.createNewFile());//创建一个新的文件,返回boolean值
    System.out.println(file.exists());//判断文件是否存在,返回Boolean值
    System.out.println(file.getPath());//获取文件相对路径,返回相对路径
    System.out.println(file.getAbsolutePath());//获取文件绝对路径,返回绝对路径
    System.out.println(file.getName());//获取文件名字,返回文件名
    System.out.println(file.isFile());//判断是否为一个文件,返回Boolean值
    System.out.println(file.isHidden());//判断是否为隐藏文件,返回Boolean值
    System.out.println(file.delete());//删除文件,返回Boolean值
    
  • 目录:

     //创建一个File对象
     File file1 = new File("C:\Users\86131\Desktop\JavaSE\IO测试\测试目录1");
     File file2 = new File("d:/测试目录2/测试目录3");
     System.out.println(file1.mkdir());//创建一个单级目录,返回Boolean值
     System.out.println(file2.mkdirs());//创建一个多级目录,返回Boolean值
     System.out.println(file1.exists());//判断目录是否存在,返回Boolean值
     System.out.println(file1.isDirectory());//判断当前路径是否为目录,返回Boolean值
     System.out.println(file1.getParentFile());//获取父级目录,返回父级目录路径
     //获取该目录下的所有文件和目录路径名,返回值为字符串数组
     String[] s = file2.list();
     for (String temp : s){
         System.out.println(temp);
     }
     System.out.println("------------------------");
     //获取该目录下的所有文件,包括文件名和绝对路径,返回文件数组
     File[] files = file2.listFiles();
     for(File temp:files){
         System.out.println(temp);
     }
    
四、常用流对象 1、文件字节流(节点流)

FileInputStream/FileOutputStream:通过字节的形式读/写文件,适合所有类型文件

FileReader/FileWriter:专门读/写文本文件

1、1文件字节输入流

主要方法:read() :读取数据

实例:读取d:/1.txt文件内容

FileInputStream fileInputStream = null;
try {
    fileInputStream = new FileInputStream("d:/1.txt");
    int temp = 0;
    while ((temp = fileInputStream.read()) != -1) {
        System.out.println(temp);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    {
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
1、2文件字节输出流

主要方法:write()和flush() :写入数据及刷新

实例:将读取到的d:/1.txt文件数据写入d:/2.txt文件中

 FileInputStream fileInputStream = null;
 FileOutputStream fos = null;
 try {
     fileInputStream = new FileInputStream("d:/1.txt");
     fos = new FileOutputStream("d:/2.txt");
     int temp = 0;
     while ((temp = fileInputStream.read()) != -1) {
         fos.write(temp);
     }
     fos.flush();//将文件从内存中写到磁盘中
 } catch (Exception e) {
     e.printStackTrace();
 } finally {
     {
         try {
             if (fileInputStream != null) {
                 fileInputStream.close();
             }
             if (fos != null) {
                 fos.close();
             }
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }
1、3通过缓冲区提高读写效率

方法一:

  • 思路:创建一个指定长度的byte数组作为缓冲区

  • 适用于读取较大的文件

  • 注意:数组大小为2的整数次幂,一般1024为最佳

  • 代码实现:

    FileInputStream fileInputStream = null;
    FileOutputStream fos = null;
    try {
        fileInputStream = new FileInputStream("d:/1.txt");
        fos = new FileOutputStream("d:/2.txt");
        byte[] buff = new byte[1024];//创建缓冲区
        int temp = 0;
        //fileInputStream.read(buff)一次读取一整个数组的数据
        while ((temp = fileInputStream.read(buff)) != -1) {
            fos.write(buff,0,temp);//写入buff内数据,从第0位开始,长度为temp
        }
        fos.flush();//将文件从内存中写到磁盘中
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

方法二:

  • 思路:创建一个由输入流对象确定长度的byte数组作为缓冲区

  • 由available()方法预估文件长度

  • 注意:不建议大文件使用,因为对内存占用较大

  • 代码实现:

    FileInputStream fileInputStream = null;
    FileOutputStream fos = null;
    try {
        fileInputStream = new FileInputStream("d:/1.txt");
        fos = new FileOutputStream("d:/2.txt");
        //通过available方法获取输入文件大小,并据此创建对应大小的数组
        byte[] buff = new byte[fileInputStream.available()];
        //因为数组大小就是文件大小了,因为只需要进行一次读写操作
        fileInputStream.read(buff);
        fos.write(buff);
        fos.flush();//将文件从内存中写到磁盘中
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

方法一、二对比:

方法一:所用内存:较小;效率:较高

方法二:所用内存:较大;效率:高

1、4通过字节缓冲流提高读写效率

BufferedInputStream和BufferedOutputStream 是字节缓冲流,是一种处理流,其原理和1、3中方法相同。

代码实现:

//新建流对象
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
    //流对象实例化
    fis = new FileInputStream("D:\1.txt");
    bis = new BufferedInputStream(fis);//缓冲流对象,套在节点流fis上
    fos = new FileOutputStream("D:\2.txt");
    bos = new BufferedOutputStream(fos);//缓冲流对象,套在节点流fos上
    int temp = 0;
    while ((temp = bis.read())!= -1){
        bos.write(temp);
    }
    bos.flush();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        //关闭流顺序:后开的先关闭
        if (bis != null) {
            bis.close();
        }
        if (fis != null) {
            fis.close();
        }
        if (bos != null) {
            bos.close();
        }
        if (fos != null) {
            fos.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
1、5定义文件拷贝工具类

代码实现:

public static void main(String[] args) {
    copyFile("d:/3.jpg","d:/4.jpg");
}
public static void copyFile(String src,String des){
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(new FileInputStream(src));
        bos = new BufferedOutputStream(new FileOutputStream(des));
        int temp = 0;
        while ((temp = bis.read())!= -1){
            bos.write(temp);
        }
        bos.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
2、文件字符流(节点流)

处理文本文件时,可以使用文件字符流

2、1文件字符输入流

主要方法:read() 读取数据

实例:读取d:/1.txt文件内容

FileReader fr = null;
try {
    fr = new FileReader("d:/1.txt");
    int temp=0;
    while ((temp = fr.read())!=-1){
        System.out.print((char) temp);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (fr!=null){
            fr.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
2、2文件字符输出流

主要方法:write()和flush() :写入数据及刷新

实例:写入字符到d:/2.txt

FileWriter fw = null;
try {
    fw = new FileWriter("d:/2.txt");
    fw.write("胡靖21130124");
    fw.flush();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (fw!=null){
            fw.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
2、3使用字符流拷贝文本文件

代码实现:

 FileReader fr = null;
 FileWriter fw = null;
 try {
     fr = new FileReader("d:/1.txt");
     fw = new FileWriter("d:/2.txt");
     char[] chars = new char[1024];
     int temp = 0;
     while ((temp = fr.read(chars)) != -1) {
         fw.write(chars, 0, temp);
     }
     fw.flush();
 } catch (Exception e) {
     e.printStackTrace();
 } finally {
     try {
         if (fr != null) {
             fr.close();
         }
         if (fw != null) {
             fw.close();
         }
     } catch (Exception e) {
         e.printStackTrace();
     }
 }
3、字符缓冲流(处理流) 3、1字符输入缓冲流

主要方法:realLine() :以行为单位读取文本文件

实例:读取d:/1.txt文件内容:

FileReader fr = null;
BufferedReader br = null;
try {
    fr = new FileReader("d:/1.txt");
    br = new BufferedReader(fr);
    String s;
    while ((s = br.readLine())!=null){//注意,这里不再是-1,而是null
        System.out.println(s);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if(br!=null){
            br.close();
        }
        if(fr!=null){
            fr.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
3、2字符输出缓冲流

主要方法:newLine() :换行

实例:写入带有换行操作的字符到d:/2.txt

FileWriter fw = null;
BufferedWriter bw = null;
try {
    fw = new FileWriter("d:/2.txt");
    bw = new BufferedWriter(fw);
    bw.write("123456");
    bw.newLine();
    bw.write("hujing");
    bw.flush();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (bw!=null){
            bw.close();
        }
        if (fw!=null){
            fw.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

思考: rn也能实现换行操作且更加便利,为何使用newLine?

答:rn为Windows系统中的换行操作,在别的系统中并不通用,使用newLine可以在任意系统中实现换行,可移植性强。

3、3定义文本拷贝工具类

代码实现:将d:/1.txt文件拷贝至d:/2.txt

public static void main(String[] args) {
    copyFile("d:/1.txt","d:/2.txt");
}
public static void copyFile(String scr,String des){
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        br = new BufferedReader(new FileReader(scr));
        bw = new BufferedWriter(new FileWriter(des));
        String temp;
        while ((temp = br.readLine())!=null){
            bw.write(temp);
            bw.newLine();
        }
        bw.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br!=null) {
                br.close();
            }
            if (bw!=null){
                bw.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
4、转换流(处理流)

InputStreamReader 和OutputStreamWriter 原来实现字节流转换成字符流

4、1键盘输入,屏幕输出
  • System.in和System.out为字节输入流和字节输出流,用于从键盘输入数据,显示屏输出数据;

代码实现:

BufferedWriter bw = null;
BufferedReader br = null;
try {System.in和System.out转换成字符流
    //通过转换流InputStreamReader和OutputStreamWriter将字节流System.in和System.out转换成字符流
    //       字符流        (字节流转字符流       (字节流    ))
    br = new BufferedReader(new InputStreamReader(System.in));
    bw = new BufferedWriter(new OutputStreamWriter(System.out));
    while (true){
        bw.write("请输入:");
        bw.flush();
        String sca = br.readLine();//程序读取控制台数据并赋给sca
        if (sca.equals("exit")){
            bw.write("结束输入");
            break;
        }
        bw.write("您输入的是:"+sca);
        bw.newLine();
        bw.flush();
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (br!=null) {
            br.close();
        }
        if (bw!=null){
            bw.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
5、字符输出流(处理流)

字符输出流 PrintWriter 中println方法可以方便的换行输出数据。

字符输入流和字符输出流不一定要配对使用

6、字节数组流(节点流)

ByteArrayInputStream 和 ByteArrayOutputStream 经常用在需要流和数组间进行转化的情况

6、1字节数组输入流

作用:将字节数组中的数据读入流中

实例:将字符串转化成字节数组并读取

public static void main(String[] args) {
    //"abcdefg"为字符串,getBytes()方法使其变成字节数组
    byte[] arr = "abcdefg".getBytes();
    StringBuilder sb = new StringBuilder();
    ByteArrayInputStream bais = null;
    try {
        //该构造方法的参数为字节数组,这个字节数组就是数据源
        bais = new ByteArrayInputStream(arr);
        int temp = 0;
        while ((temp=bais.read())!=-1){
            sb.append((char) temp);
        }
        System.out.println(sb);
    }finally {
        try {
            if (bais!=null){
                bais.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
6、2字节数组输出流

作用:将流中的数据写入字节数组中

实例:

ByteArrayOutputStream bos = null;
StringBuilder sb = new StringBuilder();
try {
    bos = new ByteArrayOutputStream();
    bos.write('a');
    bos.write('b');
    bos.write('c');
    //toByteArray():将流转换为字节数组的方法
    //arr中元素则为通过write方法写进的
    byte[] arr = bos.toByteArray();
    for(int i=0;i
        sb.append((char) arr[i]);
    }
    System.out.println(sb);
} finally {
    try {
        if (bos!=null){
            bos.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
7、数据流(处理流)

作用:当读写数据类型为基本类型时,使用DataInputStream和DataOutputStream 可以省去类型转换的麻烦

7、1数据输出流

实例:输出各个类型的数据到文件中

DataOutputStream dos = null;
try {
    //因为写入类型的原因,文件可以没有后缀,文件后缀无关紧要
    dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("d:/data")));
    dos.writeBoolean(true);//写入Boolean型
    dos.writeChar('a');//写入char型
    dos.writeInt(10);//写入int型
    dos.writeDouble(3.14);//写入double型
    dos.writeUTF("123456");//写入字符串
    dos.flush();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (dos!=null) {
            dos.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
7、2数据输入流

实例:从文件中输入各个类型数据

DataInputStream dis = null;
try {
    dis = new DataInputStream(new BufferedInputStream(new FileInputStream("d:/data")));
    //注意:读取顺序应与写入顺序一致
  
    System.out.println(dis.readBoolean());
    System.out.println(dis.readChar());
    System.out.println(dis.readInt());
    System.out.println(dis.readDouble());
    System.out.println(dis.readUTF());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (dis!=null) {
            dis.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
8、对象流

对象流能够对对象进行读写操作

8、1java对象的序列号和反序列化 8、1、1序列化和反序列化是什么

序列化:传输方把对象变成字节序列的过程

反序列化:接受方把接收到的字节序列转化成对象的过程

序列化的作用:

  • 持久性:把对象的字节序列永久的存放在硬盘内
  • 网络通信:在网络上传输对象的字节序列
8、1、2序列化涉及的类和接口

ObjectOutputStream:对象输出流,其中writeObject(Object obj)方法可以把参数指定的对象序列化

ObjectInputStream:对象输入流,其中readObject()方法可以从一个源中读取字节序列并反序列化成对象

只有实现了Serializable接口的类才能被序列化,Serializable接口是个空接口,起标记作用

8、2操作基本数据类型

同上 7、数据流

8、3操作对象 8、3、1将对象序列化到文件

注意:必须实现Serializable接口

  1. 创建对象user:

    public class user implements Serializable {//注意实现Serializable
        private String name;
        private String id;
        private int age;
        public user(String name, String id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }
        public user() {
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override//重写方法,方便打印输出
    	public String toString() {
        return "User{" +
                "name='" + name + ''' +
                ", id='" + id + ''' +
                ", age=" + age +
                '}';
    }
    }
    
  2. 序列化到文件Object:

    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("d:/object")));
        user user = new user("hj","21130124",18);
        oos.writeObject(user);//将一个对象序列化到外部
        oos.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (oos!=null) {
                oos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
8、3、2将对象反序列化到内存

代码实现:

ObjectInputStream ois = null;
try {
    ois = new ObjectInputStream(new FileInputStream("d:/object"));
    User user = (User)ois.readObject();//返回值为Object型,需强制转化为User型
    System.out.println(user);//在user类中重写了toString方法,所以可以直接输出
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (ois!=null) {
            ois.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
9、随机访问流

RandomAccessFile 功能:

  • 对文件进行读写
  • 可以访问文件任意位置

常用方法:

  • RandomAccessFile(String name,String mode) name确定文件,mode确定权限(r为可读,rw为可读写)
  • seek(long a) 确定文件读写位置,a表示距离开头的字节个数
  • getFilePointer() 获取流当前读写位置

实例:

RandomAccessFile raf = null;
try {
    raf=new RandomAccessFile("d:/raf.txt","rw");
    int[] a = new  int[]{1,2,3,4,5,6,7,8,9,10};
    for (int i = 0; i < a.length; i++) {
        raf.writeInt(a[i]);
    }
    //指针从0开始,int型为4个字节,所以距离开头4个字节为第二个int型数据
    raf.seek(4);
    //readInt方法会自动往后读四个字节
    System.out.println(raf.readInt());
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (raf!=null) {
            raf.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
10、FIle类在IO中的使用

当以文件作为数据源或目标时,除了可以使用字符串指定文件位置外,还可以使用File类指定

方法如下:

//使用字符串指定:
fileInputStream = new FileInputStream("d:/1.txt");
//使用FIle类:
fileInputStream = new FileInputStream(new File("d:/1.txt"));

作用:

当使用第三方IO包时,必须使用File类

五、ApacFileReaderhe IO包 1、简介

比JDK提供的IO类更加简单快捷**

官方网站:Welcome to The Apache Software Foundation!

2、下载和添加包

下载网址:Commons IO – Commons IO Overview (apache.org)

添加包:

  1. 下载并解压

  2. 打开IDEA项目

  3. 打开项目结构(Ctrl+shift+Alt+s)

  4. 添加java文件

  5. 选中如图文件

  1. 添加成功

3、FileUtils使用示例
 public static void main(String[] args) throws Exception{
     //utf-8:编码格式
     String s = FileUtils.readFileToString(new File(("d:/1.txt")),"utf-8");
     System.out.println(s);
 }

更多方法详见index.html文档

4、IOUtils使用示例
public static void main(String[] args) throws Exception{
    String s = IOUtils.toString(new FileInputStream("d:/1.txt"));
    System.out.println(s);
}

更多方法详见index.html文档

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1002583.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号