Java IO流详细教程

目录

一、IO介绍

IO流体系

字节流

字节输出流:FileoutputStream

字节输入流FilelnputStream

字符流

字符输入流

字符输出流

缓冲流

字节缓冲流

字符缓冲流

序列化、反序列化流

序列化/对象操作输出流

反序列化/对象操作输入流

打印流

字节打印流

字符打印流

解压缩流

解压流

压缩流

IO流工具


一、IO介绍

Java IO流是Java中处理输入输出的机制。它是一种数据传输方式,用于在程序和外部设备(例如文件、网络连接、控制台)之间传输数据。Java IO流提供了一种灵活的方式来读取和写入数据,可以处理各种类型的数据,包括文本、二进制和对象数据。Java IO流包括输入流和输出流两种类型,其中输入流用于读取数据,输出流用于写入数据。在Java中,IO流是通过类和接口来实现的。

Java IO流提供了多种类型的流,包括字节流和字符流。字节流处理的是二进制数据,可以操作所有类型的文件,而字符流处理的是文本数据,只能操作纯文本文件(纯文本文件指:用windows系统自带的记事本打开并且能读懂的文件,例如:txt文件,md文件,xml文件,lrc文件等
)。字节流包括InputStream和OutputStream,而字符流包括Reader和Writer。此外,Java IO流还提供了缓冲流、数据流、对象流等类型的流,以便更方便地处理数据。

IO流体系

字节流

字节输出流:FileoutputStream

操作本地文件的字节输出流,可以把程序中的数据写到本地文件中。

书写步骤:

1、创建字节输出流对象

2、写数据

3、释放资源

        File f1 = new File( "D:\a.txt" );
        boolean b1 = false;
        FileOutputStream fos = null;
        try {
            //在D盘创建文件
            b1 = f1.createNewFile();
            //创建输出流对象,数据传输通道
            fos = new FileOutputStream("D:\a.txt" );
            //写入数据
            fos.write(97);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(b1);

细节1:参数是字符串表示的路径或者是File对象都是可以的

        FileOutputStream fos = null;
        try {
            //创建输出流对象,数据传输通道
            fos = new FileOutputStream(new File( "D:\a.txt" ) );
            //写入数据
            fos.write(97);
           
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

细节2:如果文件不存在会创建一个新的文件,但是要保证父级路径是存在的。

细节3:如果文件已经存在,则会清空文件
细节: write方法的参数是整数,但是实际上写到本地文件中的是整数在ASCII上对应的字符

FileOutputStream写数据的3种方式

方法名称 说明
void write(int b) 一次写一个字节数据
void write(byte[ ] b) 一次写一个字节数组数据
void write(byte[ ] b, int off, int len) 一次写一个字节数组的部分数据

 方式一:

 public static void main(String[] args) {
         FileOutputStream fos = null;
        try {
            //创建输出流对象,数据传输通道
            fos = new FileOutputStream(new File( "D:\aa\a.txt" ) );
            //写入数据
            fos.write(97);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

方式二:

public static void main(String[] args) {
         FileOutputStream fos = null;
        try {
            //创建输出流对象,数据传输通道
            fos = new FileOutputStream(new File( "D:\a.txt" ) );
            byte[] bytes = {97, 98, 99, 100};
            //写入数据
            fos.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

方式三:

public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //创建输出流对象,数据传输通道
            fos = new FileOutputStream(new File( "D:\a.txt" ) );
            byte[] bytes = {97, 98, 99, 100};
            //写入数据
            //参数一:数组    参数二:起始索引    参数三:写入的个数
            //b c
            fos.write(bytes,1,2);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

换行写入:

public static void main(String[] args) {
            FileOutputStream fos = null;
        try {
            //创建输出流对象,数据传输通道
            fos = new FileOutputStream(new File( "D:\a.txt" ) );
            String str = "zhangsan";
            byte[] bytes1 = str.getBytes();
            fos.write(bytes1);

            String str2 = "rn";
            byte[] bytes2 = str2.getBytes();
            fos.write(bytes2);

            String str3 = "666";
            byte[] byte3 = str3.getBytes();
            fos.write(byte3);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

续写:

 public static void main(String[] args) {
         FileOutputStream fos = null;
        try {
            //创建输出流对象,数据传输通道
            //参数1:文件1路径     参数2:续写开关,ture续写,false文件清空从新写入
            fos = new FileOutputStream(new File( "D:\a.txt" ),true);
            String str = "zhangsan";
            byte[] bytes1 = str.getBytes();
            fos.write(bytes1);

            String str2 = "rn";
            byte[] bytes2 = str2.getBytes();
            fos.write(bytes2);

            String str3 = "666";
            byte[] byte3 = str3.getBytes();
            fos.write(byte3);
           
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

字节输入流FilelnputStream

操作本地文件的字节输入流,可以把本地文件中的数据读取到程序中来。
书写步骤:

1、创建字节输入流对象

2、读数据

3、释放资源

 public static void main(String[] args) {
         FileInputStream fis = null;
        try {
            //创建输入流对象,数据传输通道
            fis = new FileInputStream("D:\a.txt" );
            //读取数据
            int read = fis.read();
            System.out.println((char) read);
           
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

细节1:如果文件不存在,就直接报错。
细节2:读取数据,一次读一个字节,读出来的是数据在ASCII上对应的数字细节,读到文件末尾了, read方法返回 -1。

循环读取文件

public static void main(String[] args) {
         FileInputStream fis = null;
        try {
            //创建输入流对象,数据传输通道
            fis = new FileInputStream("D:\a.txt" );
            //读取数据
            int b;
            while ((b = fis.read()) != -1){
                System.out.print((char) b);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

拷贝文件

public static void main(String[] args) {
         FileInputStream fis = null;
         FileOutputStream fos = null;
        try {
            //创建输入流对象,数据传输通道
            fis = new FileInputStream("D:\a.txt" );
            //创建输出流对象,数据传输通道
            fos = new FileOutputStream("D:\b.txt");
            //读取数据,边读编写
            int b;
            while ((b = fis.read()) != -1){
                fos.write(b);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

一次读取多个字节数据

public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            //创建输入流对象,数据传输通道
            fis = new FileInputStream("D:\a.txt" );
            byte[] bytes = new byte[2];
            //读取数据,返回读取元素的个数
            int len = fis.read(bytes);
            System.out.println(len);
            //从当前数组中,从第0个元素开始,读取len个元素
            String str = new String(bytes,0,len);
            System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

字符流

字符流是Java IO流中的一种,用于处理文本数据。与字节流不同,字符流是面向字符的,可以处理Unicode字符集中的字符。Java中的字符流主要有两个类:Reader和Writer。

Reader类是抽象类,它提供了多种方法用于读取字符数据。常用的子类包括FileReader、InputStreamReader、CharArrayReader等。其中,FileReader用于读取文件中的字符数据,InputStreamReader用于读取字节流并将其转换为字符流,CharArrayReader用于读取字符数组中的数据。

Writer类也是抽象类,它提供了多种方法用于写入字符数据。常用的子类包括FileWriter、OutputStreamWriter、CharArrayWriter等。其中,FileWriter用于向文件中写入字符数据,OutputStreamWriter用于将字符流转换为字节流并写入输出流,CharArrayWriter用于向字符数组中写入数据。

与字节流不同,字符流可以自动处理字符集编码和解码的问题,因此在处理文本数据时更加方便和安全。同时,字符流也提供了缓冲区和转换器等功能,可以提高数据传输的效率。

总之,字符流是Java IO流中的一种,用于处理文本数据。它具有自动处理字符集编码和解码的功能,提供了缓冲区和转换器等功能,是处理文本数据的首选。

特点:

输入流:一次读一个字节,遇到中文时,一次读多个字节

输出流:底层会把数据按照指定的编码方式进行编码,变成字节再写到文件中

字符输入流

书写步骤:

1、创建字符输入流对象

2、读取数据

3、释放资源

public static void main(String[] args) throws IOException {
        /*
        第一步:创建对象
        public FileReader(File file)        创建字符输入流关联本地文件
        public FileReader(String pathname)  创建字符输入流关联本地文件

        第二步:读取数据
        public int read()                   读取数据,读到末尾返回-1
        public int read(char[] buffer)      读取多个数据,读到末尾返回-1

        第三步:释放资源
        public void close( )              释放资源/关流
        */

        FileReader fr = new FileReader("D:\a.txt");

        int ch;
        while ((ch = fr.read()) != -1){
            System.out.print((char) ch);
        }
        fr.close();
    }

read ()细节:
1.read():默认也是一个字节一个字节的读取的,如果遇到中文就会一次读取多个

2.在读取之后,方法的底层还会进行解码并转成十进制。最终把这个十进制作为返回值

一次读取多个字符

 public static void main(String[] args) throws IOException {
        /*
        第一步:创建对象
        public FileReader(File file)        创建字符输入流关联本地文件
        public FileReader(String pathname)  创建字符输入流关联本地文件

        第二步:读取数据
        public int read()                   读取数据,读到末尾返回-1
        public int read(char[] buffer)      读取多个数据,读到末尾返回-1

        第三步:释放资源
        public void close( )              释放资源/关流
        */

        FileReader fr = new FileReader("D:\a.txt");
        char[] chars = new char[2];
        int len;
        //read(chars):读取数据,解码,强转三步合并了,把强转之后的字符放到数组当中
        //相当于空参的read +强转类型转换
        while ((len = fr.read(chars)) != -1){
            System.out.print(new String(chars,0,len));
        }
        fr.close();
    }

字符输出流

构造方法 说明
public Filewriter(File file) 创建字符输出流关联本地文件
public Filewriter( string pathname) 创建字符输出流关联本地文件
public Filewriter(File file, boolean append) 创建字符输出流关联本地文件,续写
public Filewriter(string pathname,boolean append) 创建字符输出流关联本地文件,续写

成员方法

成员方法 说明
void write(int c) 写出一个字符
void write(string str) 写出一个字符串
void write(String str, int off, int len) 写出一个字符串的一部分
void write(char[ ] cbuf) 写出一个字符数组
void write(char[ ] cbuf, int off, int len) 写出字符数组的一部分

书写步骤:

1、创建字符输出流对象

2、写入数据

3、释放资源

 public static void main(String[] args) throws IOException {
        //创建字符输出流对象
        FileWriter fw = new FileWriter("D:\a.txt");

        //void write(int c)	写出一个字符
        fw.write(97);
        //void write(string str)	写出一个字符串
        fw.write("你好张三");
        //void write(String str, int off, int len)	写出一个字符串的一部分
        fw.write("你好张三",2,2);
        //void write(char[ ] cbuf)	写出一个字符数组
        char[] chars = {'1','2','3','你'};
        fw.write(chars);
        //void write(char[ ] cbuf, int off, int len)	写出字符数组的一部分
        fw.write(chars,2,2);
        fw.close();
    }

细节1:参数是字符串表示的路径或者File对象都是可以的
细节2:如果文件不存在会创建一个新的文件,但是要保证父级路径是存在的

细节3:如果文件已经存在,则会清空文件,如果不想清空可以打开续写开关
细节4:如果write方法的参数是整数,但是实际上写到本地文件中的是整数在字符集上对应的字符

字符流原理解析
创建字符输入流对象:

底层:关联文件,并创建缓冲区(长度为8192的字节数组)

读取数据:

1.判断缓冲区中是否有数据可以读取

2.缓冲区没有数据:就从文件中获取数据,装到缓冲区中,每次尽可能装满缓冲区如果文件中也没有数据了,返回-1

3.缓冲区有数据:就从缓冲区中读取。
空参的read方法:一次读取一个字节,遇到中文一次读多个字节,把字节解码并转成十进制返回

有参的read方法:把读取字节,解码,强转三步合并了,强转之后的字符放到数组中

拷贝文件夹,带子文件夹

 public static void main(String[] args) throws IOException {
        //拷贝一个文件夹
        //创建对象表示数据源
        File src = new File("D:\aaa\src");
        //创建对象表示拷贝目的地
        File temp = new File("D:\aaa\temp");
        //掉方法
        copyFile(src,temp);
    }

    /**
     * 拷贝文件
     * @param src 数据源
     * @param temp 目的地
     */
    private static void copyFile(File src, File temp) throws IOException {
        //创建文件夹
        temp.mkdirs();
        //递归
        //进入数据源
        File[] files = src.listFiles();
        //遍历数组
        for (File file : files) {
            if (file.isFile()){
                //拷贝文件
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(new File(temp,file.getName()));
                byte[] bytes = new byte[1024];
                int len;
                while ((len = fis.read(bytes)) != -1){
                    fos.write(bytes,0,len);
                }
                fos.close();
                fis.close();
            }else {
                //文件夹递归
                //new File(temp,file.getName()) 创建文件夹,名字file.getName()
                copyFile(file,new File(temp,file.getName()));
            }
        }
    }

缓冲流

缓冲流(Buffered Stream)是一种流式输入输出(I/O)操作的方式。通常,缓冲流会在内存中创建一个缓冲区,将数据暂时存放在缓冲区中,然后再一次性地将缓冲区中的数据写入到文件或者网络中,或者从文件或者网络中读取一定量的数据到缓冲区中,再从缓冲区中读取数据。

缓冲流的作用是提高I/O操作的效率。因为在进行I/O操作时,每次读写一个字节或者一个字符都会涉及到磁盘或者网络的访问,这样会导致I/O操作的效率非常低下。而缓冲流的使用可以将多个I/O操作合并为一次操作,从而提高I/O操作的效率。

Java中的缓冲流有两种:BufferedInputStream和BufferedOutputStream。其中,BufferedInputStream是InputStream的子类,可以提高从输入流中读取数据的效率;BufferedOutputStream是OutputStream的子类,可以提高向输出流中写入数据的效率。在使用缓冲流时,需要注意及时关闭流,避免资源泄露和数据丢失

字节缓冲流

 字节缓冲流拷贝文件

public static void main(String[] args) throws IOException {
        //创建缓冲流对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\a.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\b.txt"));
        //循环读取文件
        int len;
        while ((len = bis.read()) != -1){
            bos.write(len);
        }
        //释放资源
        bos.close();
        bis.close();
    }

一次读取多个字节

public static void main(String[] args) throws IOException {
        //创建缓冲流对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\a.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\b.txt"));
  byte[] bytes = new byte[1024];
        //循环读取文件
        int len;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }
        //释放资源
        bos.close();
        bis.close();
    }

字符缓冲流

 字符缓冲输入流特有方法 说明
public string readLine() 读取一行数据,如果没有数据可读了,会返回null
字符缓冲输出流特有方法 说明
public void newLine() 跨平台的换行

字符缓冲输入流

public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("D:\a.txt"));
        //读取数据,一次读一行
        String line = br.readLine();
        System.out.println(line);
        br.close();
    }

字符缓冲输出流

 public static void main(String[] args) throws IOException {
        //创建字符缓冲输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\a.txt"));
        //写入数据
        bw.write("123");
        //写入换行
        bw.newLine();
        bw.write("456");

        bw.close();
    }

序列化、反序列化流

Java中的序列化和反序列化可以使用ObjectOutputStream和ObjectInputStream来实现。ObjectOutputStream是OutputStream的子类,可以将对象序列化为字节流并写入到输出流中;ObjectInputStream是InputStream的子类,可以从输入流中读取字节流并反序列化为对象。

序列化和反序列化的作用是在网络传输或者持久化存储时,将对象转换为字节流进行传输或者存储,以便在需要时重新恢复对象。

序列化/对象操作输出流

构造方法 说明
public objectoutputstream(outputstream out) 把基本流包装成高级流
成员方法 说明
public final void writeobject(object obj) 把对象序列化(写出)到文件中去

注意:

  1. 序列化的对象必须实现Serializable接口,否则会抛出NotSerializableException异常。

  2. 序列化的对象中的属性也必须是可序列化的,否则也会抛出NotSerializableException异常。

  3. 序列化和反序列化的流必须在同一个JVM中,否则会抛出ClassNotFoundException异常。

  4. 序列化和反序列化的流必须及时关闭,避免资源泄露。

  5. 序列化和反序列化的过程中,可能会出现版本不兼容的问题,需要使用serialVersionUID来解决。

public static void main(String[] args) throws IOException {
        //创建对象
        Student student = new Student("张三",20);
        //创建序列化流对象/对象操作输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\a.txt"));
        //写入数据
        oos.writeObject(student);
        //释放资源
        oos.close();
    }

反序列化/对象操作输入流

可以把序列化到本地文件中的对象读取到程序中

构造方法 说明
public objectInputstream( Inputstream out) 把基本流变成高级流
成员方法 说明
public object readobject() 把序列化到本地文件中的对象,读取到程序中来
  public static void main(String[] args) throws IOException, ClassNotFoundException {
        //创建反序列化流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\a.txt"));
        //读取数据
        Student student = (Student)ois.readObject();
        //
        System.out.println(student);
        //释放资源
        ois.close();
    }

打印流

打印流(PrintStream和PrintWriter)是Java中用于输出文本信息的流。它们可以将文本信息输出到控制台、文件、网络等地方。

PrintStream是OutputStream的子类,可以将文本信息输出到字节流中,它提供了多种打印方法,如print、println、printf等,可以输出不同类型的数据。PrintStream还提供了自动刷新缓冲区的功能,可以在每次输出后自动刷新缓冲区。

PrintWriter是Writer的子类,可以将文本信息输出到字符流中,它也提供了多种打印方法,如print、println、printf等,可以输出不同类型的数据。PrintWriter还提供了自动刷新缓冲区的功能,可以在每次输出后自动刷新缓冲区。

使用打印流的好处是可以方便地输出各种类型的数据,并且可以自动刷新缓冲区,避免输出数据不完整的问题。同时,打印流还提供了格式化输出的功能,可以根据需要进行格式化输出。

在使用打印流时,需要注意及时关闭流,避免资源泄露和数据丢失。另外,需要注意打印流的输出位置和目标,避免输出到错误的位置和目标。

字节打印流

构造方法 说明
public Printstream(outputstream/File/string) 关联字节输出流/文件/文件路径
public Printstream(string fileName,charset charset) 指定字符编码
public Printstream(outputstream out, boolean autoFlush) 自动刷新
public Printstream(outputstream out,boolean autoFlush,string encoding) 指定字符编码且自动刷新
成员方法 说明
public void write(int b) 常规方法:规则跟之前一样,将指定的字节写出
public void println( Xxx Xx) 特有方法:打印任意数据,自动刷新,自动换行
public void print(Xxx xx) 特有方法:打印任意数据,不换行
public void printf(String format,0Object. .. args) 特有方法:带有占位符的打印语句,不换行
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        //创建字节打印流对象
        PrintStream ps = new PrintStream(new FileOutputStream("D:\a.txt"),true,"UTF-8");
        //写成数据
        ps.println(97);
        ps.print(true);
        ps.printf("%s爱上了%s","阿珍","阿强");

        //释放资源
        ps.close();
    }

字符打印流

构造方法 说明
public Printwriter(write/File/string) 关联字节输出流/文件/文件路径
public Printwriter( String fileName,Charset charset) 指定字符编码
public Printwriter(write w, boolean autoFlush) 自动刷新
public PrintWriter(outputStream out,boolean autoFlush,Charset charset) 指定字符编码且自动刷新
成员方法 说明
public void write(....) 常规方法:规则跟之前一样,写出字节或字符串
public void println( Xxx Xx) 特有方法:打印任意数据类型且换行
public void print(Xxx xx) 特有方法:打印任意数据,不换行
public void printf(String format,Object. .. args) 特有方法:带有占位符的打印语句
 public static void main(String[] args) throws IOException {
        //创建字符打印流的对象
        PrintWriter pw = new PrintWriter(new FileWriter("D:\a.txt"),true);
        //写数据
        pw.println("张三");
        //释放资源
        pw.close();
    }

解压缩流

解压流

解压本质:把每一个ZipEntry按照层级拷贝到本地另一个文件夹中

 public static void main(String[] args) throws IOException {
        //创建一个file表示要解压的压缩包
        File src = new File("D:\aaa.zip");
        //创建一个File表示解压的目的地
        File dest = new File("D:\");
        //掉方法
        unzip(src,dest);
    }
    //定义一个解压方法
    private static void unzip(File src, File dest) throws IOException {
        //解压的本质:把压缩包里面的每一个文件或者文件夹读取出来,按照层级拷贝到目的地当中
        //创建一个解压缩流用来读取压缩包中的数据
        ZipInputStream zip = new ZipInputStream(new FileInputStream(src));
        //要先获取到压缩包里面的每一个zipentry对象
        // 表示当前在压缩包中获取到的文件或者文件夹
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null){
            System.out.println(entry);
            if (entry.isDirectory()){
                //文件夹:需要在目的地dest处创建一个同样的文件夹
                File file = new File(dest,entry.toString());
                file.mkdirs();
            }else {
                //文件:需要读取到压缩包I的文件,并把他存放到目的地dest文件夹中(按照层级目录进行存放)
                FileOutputStream fos = new FileOutputStream(new File(dest,entry.toString()));
                int b;
                while ((b = zip.read()) != -1){
                    //写到目的地
                    fos.write(b);
                }
                //表示在压缩包中的一个文件处理完毕了。
                fos.close();
                zip.closeEntry();
            }
        }
        
        zip.close();
    }

压缩流

压缩本质:把每一个(文件/文件夹)看成ZipEntry对象放到压缩包中
压缩单个文件

public static void main(String[] args) throws IOException {
        //创建一个file表示要解压的压缩包
        File src = new File("D:\a.txt");
        //创建一个File表示解压的目的地
        File dest = new File("D:\");
        //掉方法
        tozip(src,dest);
    }

    /**
     * 压缩
     * @param src 要压缩的文件
     * @param dest 压缩包的位置
     * @throws IOException
     */
    private static void tozip(File src, File dest) throws IOException {
        //创建压缩流关联对象
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(dest,"a.zip")));
        //2.创建ZipEntry对象,表示压缩包里面的每一个文件和文件夹
        ZipEntry entry = new ZipEntry("a.txt");
        //.把ZipEntry对象放到压缩包当中
        zos.putNextEntry(entry);
        //把src文件中的数据写到压缩包当中
        FileInputStream fis = new FileInputStream(src);

        int b;
        while ((b = fis.read()) != -1){
            zos.write(b);
        }
        zos.closeEntry();
        zos.close();

    }

 压缩文件夹

public static void main(String[] args) throws IOException {
        //创建File对象表示要压缩的文件夹
        File src = new File("D:\aaa");
        //创建File对象表示压缩包放在哪里(压缩包的父级路径)
        File destParent = src.getParentFile();
        //创建File对象表示压缩包的路径
        File dest = new File(destParent,src.getName() + ".zip");
        //创建压缩流关联压缩包
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));
        //获取src里面的每一个文件,变成ZipEntry对象,放入到压缩包当中
        tozip(src,zos,src.getName());

        zos.close();
    }

    /**
     * 获取src里面的每一个文件,变成ZipEntry对象,放入到压缩包当中
     * @param src 数据源
     * @param zos 压缩流
     * @param name 压缩包内部的路径
     */
    private static void tozip(File src, ZipOutputStream zos, String name) throws IOException {

        //
        File[] files = src.listFiles();

        for (File file : files) {
            if (file.isFile()){
                //
                ZipEntry entry = new ZipEntry(name + "\" + file.getName());
                zos.putNextEntry(entry);
                //
                FileInputStream fis = new FileInputStream(file);
                int b;
                while ((b = fis.read()) != -1){
                    zos.write(b);
                }
                fis.close();
                zos.closeEntry();
            }else {
                tozip(file,zos,name + "\" + file.getName());
            }
        }
    }

IO流工具

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

常见方法:

FileUtils类(文件/文件夹相关) 说明
static void copyFile(File srcFile,File destFile) 复制文件
static void copyDirectory(File srcDir,File destDir) 复制文件夹
static void copyDirectoryToDirectory(File srcDir, File destDir) 复制文件夹
static void deleteDirectory(File directory) 删除文件夹
static void cleanDirectory(File directory) 清空文件夹
static string readFileToString(File file,Charset encoding) 读取文件中的数据变成成字符串
static void write(File file,CharSequence data,string encoding) 写出数据
IOUtils类(流相关相关) 说明
public static int copy(InputStream input,outputStream output) 复制文件
public static int copyLarge(Reader input,writer output) 复制大文件
public static string readLines(Reader input) 读取数据
public static void write(String data,outputstream output) 写出数据

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>