Xiaobai learns Java: RandomAccessFile

Previous portal: Xiaobai learns Java: I / O flow

Xiaobai learns Java: RandomAccessFile

All the streams we learned before are read-only or write only when operating on data. It is difficult to update the files opened with these streams. Java provides the RandomAccessFile class, which allows reading and writing anywhere in the file.

summary

The interpretation of the official document is as follows:

Inheritance and Implementation

RandomAccessFile directly inherits from the object class. It doesn't look like so many input and output streams we learned before. They all inherit from the abstract base class. However, RandomAccessFile can complete the input and output of files through the implementation of the interface:

public class RandomAccessFile implements DataOutput,DataInput,Closeable

When viewing official documents, we see many similar words. We take the read method as an example:

Although RandomAccessFile is not a subclass of InputStream, the behavior of this method is the same as that of InputStream The read () method is identical.

We can infer that the related methods such as read and write are the same as the read and write operations we have learned before.

constructor

Let's take a look at the constructor it provides:

RandomAccessFile(File file,String mode) 

RandomAccessFile(String name,String mode) 

Only these two constructors mean to create a stream that supports random access to files. Mode is a parameter to set the access method. The former passes in the file object and the latter passes in the pathname.

Mode setting

I still understand the functions of the first two, but I don't understand "RWS" and "RWD". I can only take a rough look at the official explanation:

We can probably understand that when we write a large amount of data, we usually store the data in the memory first and then engrave it into the underlying storage device. In this way, the written data may not be stored in time, such as sudden power failure. "RWD" and "RWS" can ensure that the written data does not pass through memory and is synchronized to the underlying storage to ensure that key information will not be lost in case of system crash.

field name pointer

As mentioned above, there is such a thing as file pointer, which can control the reading or writing position. Here are several methods related to file pointer:

//将指针位置设置为pos,即从流开始位置计算的偏移量,以字节为单位
public void seek(long pos)
//获取指针当前位置,以字节为单位
public native long getFilePointer()
//跳过n个字节的便宜量
public int skipBytes(int n)

Note: in bytes, it means that if 1 int type content is read, the pointer will move 4 bytes after reading.

Operation data

Read data

Suppose you now read from a file containing only 8 bytes:

    //指针测试
    System.out.println("首次进入文件,文件指针的位置:"+raf.getFilePointer());//0
    raf.seek(4);
    System.out.println("seek后,现在文件指针的位置:"+raf.getFilePointer());//4
    raf.skipBytes(1);
    System.out.println("skipBytes后,现在文件指针的位置:"+raf.getFilePointer());//5

The following are the test methods:

    public static void testFilePointerAndRead(String fileName){
        //try-with-resource
        try(RandomAccessFile raf = new RandomAccessFile(fileName,"r")){
            //定义缓冲字节数组
            byte[] bs = new byte[1024];
            int byteRead = 0;
            //read(bs)  读取bs.length个字节的数据到一个字节数组中
            while((byteRead = raf.read(bs))!=-1){
                System.out.println("读取的内容:"+new String(bs,byteRead));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Read (byte B []) and read ()

Differences between read (byte b[]) and read () methods

public int read()

The return value of this method is the next byte from the file pointer. The byte is returned as an integer, ranging from 0 to 255 (0x00-0x0ff). - 1 if the end of the file is reached. When I write the a character in bytes, when I view it in the text file, it is a complete A. I understand that this is an internal conversion.

When I call the read () method again, it will still return 97, because the return value of read must be of type int, and the corresponding conversion must be carried out to get the character a.

These are really no problems, but when we read the content in the above code, there is no conversion. Of course, this is my idea at the beginning. Let's take a look at the read (byte B []) method. We'll understand it after reading it.

public int read(byte b[])

The return value of this method is the total number of bytes read into the buffer array B. if there is no more data, it is - 1 because the end of the file has been reached.

Take our code as an example: we have defined an array BS for storing bytes. Bytes are read from files, We specifically define a variable byteread to represent the return value of the method (that is, the number of bytes read into the buffer array). If it is - 1, it means that the end is reached. If it is not - 1, we call the construction method of string, start from bit 0 of the byte array, read the bytes of byteread length backward, and construct a string.

String constructor is a bit particular. It will decode the specified byte array by using the platform's default character set to construct a new string. In fact, this constructor has completed the conversion from byte array to character.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>