Home > Java > javaTutorial > body text

Analysis of I/O input and output examples in Java

WBOY
Release: 2023-05-13 15:40:06
forward
1465 people have browsed it

    Preface

    The data stored in variables, arrays and objects are temporary and will be lost after the program ends. In order to be able to save the created data permanently, it needs to be saved in disk files so that they can be used in other programs. Java's I/O technology can save data into text files, binary files and even ZIP compressed files, meeting the requirements for permanent data storage. Mastering I/O processing technology can improve data processing capabilities.

    1. Stream Overview

    A stream is a set of ordered data sequences. According to the type of operation, it can be divided into two types: input stream and output stream. The I/O (Input/Output) stream provides a channel program that can be used to send a sequence of bytes from the source to the destination. Although I/O streams are usually associated with disk file access, the source and destination of a program can also be the keyboard, mouse, memory, or monitor window.
    Java handles input/output mode by data stream. The program reads the data in the source from the input stream pointing to the source. The source can be a file, network, compressed package or other data source.
    The output stream points to the destination where the data is to be reached. The program transfers information to the destination by writing data to the output stream.

    2. Input/Output Stream

    The Java language defines many classes that are specifically responsible for various forms of input/output. Such classes are placed in the java.io package. Among them, all input stream classes are subclasses of abstract class InputStream (byte input stream) or abstract class Reader (character input stream); and all output streams are abstract class OutputStream (byte output stream) or abstract class Writer ( A subclass of character output stream).

    1. Input stream

    The InputStream class is an abstract class of byte input streams and the parent class of all byte input streams. The specific hierarchy of the InputStream class is as follows.
    All methods in this class will throw IOException when encountering an error. Below is a brief description of some of the methods in this class.

    read() method: Read the next byte of data from the input stream. Returns an int byte value in the range 0-255. If no bytes are available because the end of the stream has been reached, the return value is -1.
    read(byte[] b): Read a certain length of bytes from the input stream and return the number of bytes in the form of an integer.
    mark(int readlimit) method: Place a mark at the current position of the input stream. The readlimit parameter tells this input stream the number of bytes allowed to be read before the mark position expires.
    reset() method: Return the input pointer to the current mark.
    skip(long n) method: Skip n bytes on the input stream and return the actual number of bytes skipped.
    markSupported() method: Returns true if the current stream supports mark()/reset() operations.
    close method: Close this input stream and release all system resources associated with the stream.

    Characters in Java are Unicode encoded and are double-byte. InputStream is used to process bytes and is not suitable for processing character text. Java provides a separate set of Reader classes for the input of character text. However, the Reader class is not a replacement for the InputStream class. It only simplifies programming when processing strings. The Reader class is an abstract class of character input streams, and all implementations of character input streams are its subclasses.

    The methods in the Reader class are similar to those in the InputStream class. Readers can check the JDK documentation when needed.

    2. Output stream

    The OutputStream class is an abstract class of byte output stream. This abstract class is the super class of all classes that represent output byte streams.
    All methods in the OutputStream class return void, and an IoException is thrown when an error is encountered. The following is a brief introduction to the methods in the OutputStream class.

    write(int b) method: Write the specified bytes to this output stream.
    write(byte[] b) method: Write b bytes from the specified byte array to this output stream.
    write(byte[] b, int off, int len) method: Write len bytes starting from offset off in the specified byte array to this output stream.
    flush() method: completely complete the output and clear the buffer area.
    close() method: Close the output stream.

    3. File class

    The File class is the only object in the java.io package that represents the disk file itself. The File class defines some platform-independent methods to operate files. You can create, delete, rename files and other operations by calling methods in the File class. Objects of the File class are mainly used to obtain some information about the file itself, such as the directory where the file is located, the length of the file, file read and write permissions, etc. Data streams can write data to files, and files are also the most commonly used data media for data streams.

    1. File creation and deletion

    You can use the File class to create a file object. The following 3 construction methods are usually used to create file objects.

    1. File(String pathname)

    This constructor creates a new File instance by converting the given pathname string into an abstract pathname.

    The syntax is as follows:

    new File(String pathname);

    Among them, pathname specifies the path name (including the file name). For example:

    File file = new File(“d:/1.txt”);

    2. File(String parent,String child)

    This constructor creates a new File object based on the defined parent path and child path strings (including file names).

    The syntax is as follows:

    new File(String parent,String child);

    3. File(File f,String child)

    This constructor creates a new File instance based on the Parent abstract path name and child path name string.

    The syntax is as follows:

    new File(File f,String child);

    2. Get file information

    File class Provides many methods for obtaining some information about the file itself. As shown in the following table

    Method | Return value | Description
    -------- | -----
    getName() | String| Get the name of the file
    canReda()| boolean | Determine whether the file is readable
    canWrite()| boolean | Determine whether the file can be written
    exits()|boolean | Determine whether the file exists
    length()|long | Get the length of the file (in bytes)
    getAbsolutePath() | String | Get the absolute path of the file
    getParent() | String | Get the parent path of the file
    isFile() | boolean | Judge Whether the file exists
    isDirectory() | boolean | Determine whether the file is a directory
    isHidden() | boolean | Determine whether the file is a hidden file
    lastModified() | long | Get the last modified time of the file

    4. File input/output stream

    During the running of the program, most of the data is operated in memory. When the program ends or is closed, these data will disappear. If you need to save the data permanently, you can use the file input/output stream to establish a connection with the specified file and save the required data to the file permanently.

    1. FillInputStream and FileOutputStream classes

    FileInputStream class and FileOUTputStream class are both used to operate disk files. If the user's file reading needs are relatively simple, you can use the FileInputString class, which inherits from the InputString class. The FileOutputStream class corresponds to the FileInputStream class and provides basic file writing capabilities. The FileOutputStream class is a subclass of the OutputStream class.
    The commonly used construction methods of the FileInputStream class are as follows:

    FileInputStream(String name)
    FileInputStream(File file)

    2, FileReader and FileWriter classes

    There is one shortcoming in using the FileOutputStream class to write data to a file and using the FileInputStream class to read content from a file. That is, both classes only provide methods for reading bytes or byte arrays. . Since Hanzi occupies two bytes in the file, if you use a byte stream, garbled characters may appear if the reading is not good. In this case, using the character stream Reader or Writer class can avoid this phenomenon.

    FileReader and FileWriter character streams correspond to the FileInputStream and FileOutputStream classes. The FileReader stream reads the file sequentially. As long as the stream is not closed, each call to the read() method sequentially reads the rest of the source content until the end of the source or the stream is closed.

    5. Input/output stream with cache

    Cache is a performance optimization of I/O. Cache streams add a memory cache area to I/O streams. With the buffer area, it is possible to execute the skip(), mark() and reset() methods on the stream.

    1. BufferedInputStream and BufferedOutputStream classes

    The BufferedInputStream class can wrap all InputStream classes with buffers to optimize performance. The BufferedInputStream class has two construction methods:

    BufferedInputStream(InputStream in)
    BufferedInputStream(InputStream in, int size)

    The first construction method creates a A 32-byte buffer. The second construction method creates a buffer of the specified size.

    2. BufferedReader and BufferedWriter classes

    The BufferedReader class and BufferedWriter class inherit the Reader class and Writer class respectively. Both classes also have internal caching mechanisms and can perform input/output in units of lines.

    6. Data input/output streams

    Data input/output streams (DataInputStream class and DataOutputStream class) allow applications to read basic Java data from the underlying input stream in a machine-independent manner. type. In other words, when reading a piece of data, you no longer have to worry about what kind of byte the value should be.

    7. ZIP Compression Input/Output Stream

    ZIP compression management file (ZIP archive) is a very typical form of file compression, which can save storage space. Regarding the I/O implementation of ZIP compression, Java's built-in classes provide very useful related classes, so its implementation is very simple. This section will introduce the use of ZipOutputStream and ZipInputStream classes in the java.util.zip package to achieve file compression/decompression. If you want to read a file from a ZIP compressed management file, you must first find the "directory entry point" of the corresponding file (from which you can know the location of the file in the ZIP file) before you can read the content of the file. If you want to write the file content into a ZIP file, you must first write the "directory entry point" corresponding to the file, and move the location where the file content is to be written to the location pointed to by this entry point, and then write the file content.

    Java实现了I/O数据流与网络数据流的单一接口,因此数据的压缩、网络传输和解压缩的实现比较容易。ZipEntry类产生的对象,是用来代表一个ZIP压缩文件内的进入点(entry)。ZipInputStream用来写出ZIP压缩格式的文件,所支持的包括已压缩及未压缩的进入点(entry)。

    ZipOutputStream类用来写出ZIp压缩格式的文件,而且所支持的包括已压缩及未压缩的进入点(entry)。下面介绍利用ZipEntry、

    ZipInputStream和ZipOutputStream3个Java类实现ZIP数据压缩方式的编程方法。

    1、压缩文件

    利用ZipOutputStream类对象,可将文件压缩为.zip文件。ZipOutputStream类的构造方法如下:

    ZipOutputStram(OutputStream out);

    ZipOutputStream类的常用方法如表所示:

    方法 返回值 说明
    putNextEntry(ZipEntry e) void 开始写一个新的ZipEntry,并将流内的位置移至此entry所指数据的开头
    write(byte[] b,int off,int len) void 将字节数组写入当前ZIP条目数据
    finish() void 完成写入ZIP输出流的内容,无须关闭它所配合的OutputStream
    setComment(String comment) void 可设置此ZIP文件的注释文字

    2、解压缩ZIP文件

    ZipInputStream类可读取ZIP压缩格式的文件,包括已压缩和未压缩的条目(entry)。ZipInputStream类的构造方法如下:

    ZipInputStream(InputStream in)

    ZipInputStream类的常用方法如下表所示:

    方法 返回值 说明
    read(byte[] b, int off , int len) int 读取目标b数组内off偏移量的位置,长度是len字节
    available() int 判断是否已读完目前entry所指定的数据。已读完返回0,否则返回1
    closeEntry() void 关闭当前ZIP条目并定位流以读取下一个条目
    skip(long n) long 跳过当前ZIP条目中指定的字节数
    getNextEntry() ZipEntry 读取下一个ZipEntry,并将流内的位置移至该entry所指数据的开头
    createZipEntry(String name) ZipEntry 以指定的name参数新建一个ZipEntry对象

    补充:获取目录下的所有目录和文件

    示例:假设目录“D:\TestDir1”下有两个文件夹(dir1 和 dir2)和一个文件 file1.txt 。

    File[] listFiles()方法:获取该目录下的所有子目录和文件,返回File类数组。

    import java.io.File;
     
    /**
     * 获取目录下的所有目录和文件
     * @author pan_junbiao
     **/
    public class DirFileTest
    {
        public static void main(String[] args)
        {
            File file = new File("D:\\TestDir1");
     
            //判断目录是否存在
            if (!file.exists())
            {
                System.out.println("目录不存在");
                return;
            }
     
            //获取文件数组
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++)
            {
                //判断是否为目录
                if (fileList[i].isDirectory())
                {
                    System.out.println("目录:" + fileList[i].getName());
                }
                else
                {
                    System.out.println("文件:" + fileList[i].getName());
                }
            }
        }
    }
    Copy after login

    执行结果:

    Analysis of I/O input and output examples in Java

    The above is the detailed content of Analysis of I/O input and output examples in Java. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template