Java-I/O stream [Learning RandomAccessFile]

RandomAccesseFile

        RandomAccess has the function of reading and writing file data, and can start to perform the operation of reading and writing data from any position of the file randomly. RandomAccessFile can open the file as read-only or read-write, depending on the method used to create it.

Reference book "Introduction to Java Basics"

Constructor of RandomAccessFile

RandomAccesseFile(File file,String mode) Use the parameter file to specify the file to be accessed, and use mode to specify the access mode
RandomAccesseFile(String name,String mode) Use the parameter name to specify the path of the accessed file, and use mode to specify the access method

The parameter mode has 4 values:

        1. r: means to open the file in read-only mode. If it is opened in read-only mode and then writes to the RandomAccessFile object, an I/OException will be thrown.

        2. rw: means to open the file in "read and write" mode. If the file does not exist, it will be created automatically.

        3. rws: means to open the file in "read and write" mode. In contrast to "rw", it requires that every update to the file's content or metadata be written synchronously to the underlying storage device.

        4. rwd: means to open the file in "read and write" mode. In contrast to "rw", it requires that every update to the contents of the file be written synchronously to the underlying storage device.

The RandomAccessFile object contains a record pointer to the current read/write location. When the program creates a new RandomAccessFile object, the file record pointer of the object will appear at the beginning of the file (that is, the position indicated as 0), and when n bytes are read, the file record pointer will move back by n bytes. In addition to being able to read and write sequentially, the RandomAccessFile object can also move the record pointer freely, either forward or backward. '

Common methods of RandomAccessFile

long getFilePointer() Returns the current position of the read/write pointer
void seek(long pos) Set the position of the read-write pointer, which is pos bytes away from the beginning of the file
int skipBytes(int n) Make the read and write pointer start from the current position, skipping n bytes
void write(byte[ ]  b) Writes the specified byte array to this file, starting at the current file pointer
void setLength(long newLength) Set the length of this file
final String readLine() Read the content of the next line from the current pointer of the specified file

        Example 1: Some video software requires payment when watching video software, but generally there are several free viewing opportunities. The following uses RandomAccessFile to simply record the number of software trials. The initial number is 3, watch the video once, and reduce it once.

Create a new test.txt file and enter the number 3 as the number of software trials (the file is placed under the project)

Trial count simulation code:


import java.io.*;

public class RandomAccessFileTest {
	public static void main(String[] args) {
		
		RandomAccessFile raf = null;
		
		try {
			//创建RandomAccessFile对象,并以读写模式打开文件test.txt文件,rw:读写
			//直接放在项目下路径为test.txt 如果放在src目录下路径为"src/test.txt"
			raf = new RandomAccessFile("test.txt","rw");
			
			//读取还可以免费观看的次数,第一次读取时view为3
			int view = Integer.parseInt(raf.readLine());
			
			//判断剩余次数
			if(view > 0) {
				//(每观看一次,次数就减少一次)
				view = view -1;
				System.out.println("您还可以免费观看 " + view + "次");
				
				//将记录指针重新指向文件开头
				raf.seek(0);
				//将剩余次数再次写入文件
				raf.write((view + "").getBytes());
			}else {
				System.out.println("您的观看次数已经用完了!");
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(raf != null) {
				try {
					raf.close();//关闭
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}

		
	}
	
}

 Try it out:

        Console:

         test.txt file

 

        Example 2: RandomAccessFile uses the seek() method to read the content at the specified location

Create a new random.txt file under the project without adding content.

Read the content code of the specified location: (3 characters away from the file, read 6 bytes)

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTest02 {
	public static void main(String[] args) throws IOException {
		//创建RandomAccessFile对象,并以读写模式打开文件random.txt文件,rw:读写
		RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
		//random.txt中写入内容
		raf.write("RandomAccessFile".getBytes());
		
		raf.seek(3);//设置读写指针的位置,与文件开头相隔3个字节数
		
		//读取 
		byte[] buf = new byte[6];
		int len = raf.read(buf);//读取6个字节
		System.out.println(new String(buf,0,len));
		raf.close(); // 关闭
	}
}

random.txt after writing the content:

Read content:

 

Guess you like

Origin blog.csdn.net/m0_51315555/article/details/124130945