Java IO stream detailed tutorial

Table of contents

1. Introduction to IO

IO stream system

byte stream

Byte output stream: FileoutputStream

Byte input stream FilelnputStream

character stream

character input stream

character output stream

buffered stream

byte buffer stream

character buffer stream

Serialization and deserialization streams

Serialization/Object Operation Output Stream

Deserialize/Object Manipulate Input Stream

print stream

Byte print stream

Character print stream

Decompress stream

Decompress stream

Compressed stream

IO streaming tool


1. Introduction to IO

Java IO stream is a mechanism for processing input and output in Java. It is a data transfer method used to transfer data between programs and external devices (such as files, network connections, consoles). Java IO streams provide a flexible way to read and write data and can handle various types of data, including text, binary and object data. Java IO streams include two types: input streams and output streams, where input streams are used to read data and output streams are used to write data. In Java, IO streams are implemented through classes and interfaces.

Java IO streams provide multiple types of streams, including byte streams and character streams. The byte stream processes binary data and can operate on all types of files, while the character stream processes text data and can only operate on plain text files (plain text files refer to: open it with the Notepad that comes with the Windows system and can read it. files, such as: txt files, md files, xml files, lrc files, etc.
). Byte streams include InputStream and OutputStream, while character streams include Reader and Writer. In addition, Java IO streams also provide buffer streams, data streams, object streams and other types of streams to facilitate data processing.

IO stream system

byte stream

Byte output stream: FileoutputStream

By operating the byte output stream of a local file, you can write the data in the program to the local file.

Writing steps:

1. Create a byte output stream object

2. Write data

3. Release resources

        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);

Detail 1: The parameter is a path represented by a string or a File object.

        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();
                }
            }
        }


Detail 2: If the file does not exist, a new file will be created, but make sure the parent path exists.

Detail 3: If the file already exists, the file will be cleared.
Detail: The parameter of the write method is an integer, but what is actually written to the local file is the ASCII character corresponding to the integer.

3 ways to write data with FileOutputStream

method name illustrate
void write(int b) Write data one byte at a time
void write(byte[ ] b) Write byte array data one at a time
void write(byte[ ] b, int off, int len) Write part of the data one byte array at a time

 method one:

 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();
                }
            }
        }
    }

Method two:

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();
                }
            }
        }
    }

Method three:

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();
                }
            }
        }
    }

Write on a new line:

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 = "\r\n";
            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();
                }
            }
        }
    }

Continuation:

 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 = "\r\n";
            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();
                }
            }
        }
    }

Byte input stream FilelnputStream

By operating the byte input stream of a local file, the data in the local file can be read into the program.
Writing steps:

1. Create a byte input stream object

2. Read data

3. Release resources

 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();
                }
            }
        }
    }

Detail 1: If the file does not exist, an error will be reported directly.
Detail 2: Read data, one byte at a time. What is read is the numerical details corresponding to the data in ASCII. When the end of the file is reached, the read method returns -1.

Read files in a loop

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();
                }
            }
        }
    }

Copy files

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();
                }
            }
        }
    }

Read multiple bytes of data at once

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();
                }
            }
        }
    }

character stream

Character stream is a type of Java IO stream, used to process text data. Unlike byte streams, character streams are character-oriented and can handle characters in the Unicode character set. There are two main classes of character streams in Java: Reader and Writer.

The Reader class is an abstract class that provides a variety of methods for reading character data. Commonly used subclasses include FileReader, InputStreamReader, CharArrayReader, etc. Among them, FileReader is used to read character data in files, InputStreamReader is used to read byte streams and convert them into character streams, and CharArrayReader is used to read data in character arrays.

The Writer class is also an abstract class that provides a variety of methods for writing character data. Commonly used subclasses include FileWriter, OutputStreamWriter, CharArrayWriter, etc. Among them, FileWriter is used to write character data to the file, OutputStreamWriter is used to convert the character stream into a byte stream and write it to the output stream, and CharArrayWriter is used to write data to the character array.

Unlike byte streams, character streams can automatically handle character set encoding and decoding, making it more convenient and safer to process text data. At the same time, character streams also provide functions such as buffers and converters, which can improve the efficiency of data transmission.

In short, character stream is a kind of Java IO stream, used to process text data. It has the function of automatically handling character set encoding and decoding, provides functions such as buffers and converters, and is the first choice for processing text data.

Features:

Input stream: read one byte at a time, when encountering Chinese, read multiple bytes at a time

Output stream: The bottom layer will encode the data according to the specified encoding method, turn it into bytes and then write it to the file.

character input stream

Writing steps:

1. Create a character input stream object

2. Read data

3. Release resources

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 () details:
1.read(): By default, it also reads byte by byte. If it encounters Chinese, it will read multiple at a time.

2. After reading, the bottom layer of the method will also be decoded and converted into decimal. Finally, this decimal is used as the return value

Read multiple characters at once

 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();
    }

character output stream

Construction method illustrate
public Filewriter(File file) Create a character output stream associated with a local file
public Filewriter( string pathname) Create a character output stream associated with a local file
public Filewriter(File file, boolean append) Create a character output stream associated with the local file and continue writing
public Filewriter(string pathname,boolean append) Create a character output stream associated with the local file and continue writing

member method

member method illustrate
void write(int c) write a character
void write(string str) write a string
void write(String str, int off, int len) Write out part of a string
void write(char[ ] cbuf) Write out a character array
void write(char[ ] cbuf, int off, int len) Write out part of a character array

Writing steps:

1. Create a character output stream object

2. Write data

3. Release resources

 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();
    }

Detail 1: The parameter is a path represented by a string or a File object.
Detail 2: If the file does not exist, a new file will be created, but the parent path must exist.

Detail 3: If the file already exists, the file will be cleared. If you do not want to clear it, you can turn on the continuation switch.
Detail 4: If the parameter of the write method is an integer, but what is actually written to the local file is the character corresponding to the integer in the character set.

Character stream principle analysis
Create character input stream object:

Bottom layer: associate files and create a buffer (byte array of length 8192)

Read data:

1. Determine whether there is data in the buffer that can be read

2. There is no data in the buffer: Get the data from the file, load it into the buffer, and fill the buffer as much as possible each time. If there is no data in the file, return -1

3. There is data in the buffer: read from the buffer.
The read method with empty parameters: reads one byte at a time, reads multiple bytes at a time when encountering Chinese, decodes the bytes and converts them into decimal and returns

The read method with parameters: combines the three steps of reading bytes, decoding, and forced conversion, and puts the characters after forced conversion into an array

Copy folder, with subfolders

 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

Buffered Stream is a method of streaming input and output (I/O) operations. Usually, a buffered stream creates a buffer in memory, temporarily stores data in the buffer, and then writes the data in the buffer to a file or network all at once, or reads a certain amount of data from a file or network. amount of data into the buffer, and then read the data from the buffer.

The function of buffered streams is to improve the efficiency of I/O operations. Because when performing I/O operations, each time reading or writing a byte or character involves disk or network access, this will cause the I/O operation to be very inefficient. The use of buffered streams can combine multiple I/O operations into one operation, thereby improving the efficiency of I/O operations.

There are two types of buffered streams in Java: BufferedInputStream and BufferedOutputStream. Among them, BufferedInputStream is a subclass of InputStream, which can improve the efficiency of reading data from the input stream; BufferedOutputStream is a subclass of OutputStream, which can improve the efficiency of writing data to the output stream. When using buffered streams, you need to pay attention to closing the stream in time to avoid resource leakage and data loss.

byte buffer stream

 Byte buffered stream copy file

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();
    }

Read multiple bytes at once

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();
    }

character buffer stream

 Character buffer input stream-specific methods illustrate
public string readLine() Read a row of data. If there is no data to read, null will be returned.
Character buffered output stream-specific methods illustrate
public void newLine() Cross-platform line breaks

Character buffered input stream

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();
    }

Character buffered output stream

 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();
    }

Serialization and deserialization streams

Serialization and deserialization in Java can be implemented using ObjectOutputStream and ObjectInputStream. ObjectOutputStream is a subclass of OutputStream, which can serialize objects into byte streams and write them to the output stream; ObjectInputStream is a subclass of InputStream, which can read byte streams from the input stream and deserialize them into objects.

The function of serialization and deserialization is to convert objects into byte streams for transmission or storage during network transmission or persistent storage, so that the objects can be restored when needed.

Serialization/Object Operation Output Stream

Construction method illustrate
public objectoutputstream(outputstream out) Wrap basic streams into advanced streams
member method illustrate
public final void writeobject(object obj) Serialize (write) the object to a file

Notice:

  1. The serialized object must implement the Serializable interface, otherwise a NotSerializableException will be thrown.

  2. The properties in the serialized object must also be serializable, otherwise a NotSerializableException will be thrown.

  3. The serialized and deserialized streams must be in the same JVM, otherwise a ClassNotFoundException will be thrown.

  4. Serialization and deserialization streams must be closed in time to avoid resource leakage.

  5. During the serialization and deserialization process, version incompatibility may occur, which needs to be solved by using 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();
    }

Deserialize/Object Manipulate Input Stream

Objects serialized to local files can be read into the program

Construction method illustrate
public objectInputstream( Inputstream out) Convert basic flow into advanced flow
member method illustrate
public object readobject() Read the object serialized into the local file into the program

  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();
    }

print stream

Print streams (PrintStream and PrintWriter) are streams used to output text information in Java. They can output text information to the console, files, network, etc.

PrintStream is a subclass of OutputStream, which can output text information into a byte stream. It provides a variety of printing methods, such as print, println, printf, etc., which can output different types of data. PrintStream also provides the function of automatically refreshing the buffer, which can automatically refresh the buffer after each output.

PrintWriter is a subclass of Writer that can output text information into a character stream. It also provides a variety of printing methods, such as print, println, printf, etc., which can output different types of data. PrintWriter also provides the function of automatically refreshing the buffer, which can automatically refresh the buffer after each output.

The advantage of using a print stream is that it can easily output various types of data, and the buffer can be automatically refreshed to avoid the problem of incomplete output data. At the same time, the print stream also provides the function of formatted output, which can be formatted as needed.

When using the print stream, you need to pay attention to closing the stream in time to avoid resource leakage and data loss. In addition, you need to pay attention to the output location and destination of the print stream to avoid outputting to the wrong location and destination.

Byte print stream

Construction method illustrate
public Printstream(outputstream/File/string) Associated byte output stream/file/filepath
public Printstream(string fileName,charset charset) Specify character encoding
public Printstream(outputstream out, boolean autoFlush) Auto Refresh
public Printstream(outputstream out,boolean autoFlush,string encoding) Specify character encoding and automatically refresh
member method illustrate
public void write(int b) Conventional method: The rules are the same as before, write out the specified bytes
public void println( Xxx Xx) Unique methods: print arbitrary data, automatically refresh, and automatically wrap lines
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) 写出数据

Guess you like

Origin blog.csdn.net/qi341500/article/details/130938030