Java: read and write access to file content

Posted by JeremyMorgan on Thu, 30 Apr 2020 12:25:23 +0200

RandomAccessFile class is a java provided access class for file content, which can read or write files.

The RandomAccessFile class supports random access to files, that is, any location where files can be accessed.

(1)java's file model

The files on the hard disk are stored in byte, which is a collection of data

(2) There are two modes to open a file

"rw" (read-write) can read and write files

"r" (read only) can only read files

Code example: RandomAccessFile RAF = new RandomAccessFile (file, "rw")

File pointer: when opening a file, the pointer is at the beginning of pointer=0;

(3) Writing method

raf.write(int) -- only one byte (last 8 bits) can be written at a time. If an int type is passed in, you need to write four times, and then the pointer points to the next position, ready to write again

(4) Reading method

int -- read a byte at the position where the pointer is, and then operate the byte into an integer

(5) Remember to close the io stream after reading and writing the file (official warning from Oracle)

Specific code example:

package demo2;

import java.util.Arrays;
import java.util.RandomAccess;

public class RafDemo {

	public static void main(String[] args) throws IOException {
		// Create file objects in memory
		File demo = new File("demo");// If the path is not filled, it will be created in the project folder by default
		// Create a file (folder) if it does not exist
		if (!demo.exists()) {
			// create folder
		// Create a raf.dat file with the demo folder as the parent directory
		File file = new File(demo, "raf.dat");
		if (!file.exists()) {
			// Create if it doesn't exist
		// Read and write

		// Specify the objects to read and write and select the read and write mode
		RandomAccessFile raf = new RandomAccessFile(file, "rw");
		// View pointer position
		System.out.println("View pointer position for the first time" + "There are" + raf.getFilePointer() + "Characters");
		// Write can only write one byte at A time, so only the lower eight bits of A will be written in
		raf.write('A');// Only one byte was written in
		// View pointer position
		System.out.println("View pointer position for the second time" + "There are" + raf.getFilePointer() + "Characters");
		// Write i in
		System.out.println("View pointer position for the third time" + "There are" + raf.getFilePointer() + "Characters");
		int i = 0x7fffffff;
		// Write method can only write one byte at a time. If int is 4 bytes or 32 bits, write it four times
		// If you move 24 bits to the right, the high octet will become the low octet, and you can write in the high octet. If you don't understand this, you can first look at binary related knowledge.

		raf.write(i >>> 24);
		raf.write(i >>> 16);
		raf.write(i >>> 8);
		System.out.println("4th pointer position:" + "There are" + raf.getFilePointer() + "Characters");
		// In fact, there are corresponding methods to write int directly. The above displacement writing is his underlying principle
		// Try to write Chinese
		String s = "in";// The default utf-16be code in java is used when typing this string

		byte[] gbk = s.getBytes("GBK");// Convert it to gbk code here
		// View file length
		System.out.println("File length is" + raf.length() + "byte");
		 * Java It is double byte encoding, and utf-16be encoding is adopted,
		 * write() here writes A, B and i to the default utf-16be code of Java,
		 * In utf-16be, both Chinese and English take up two bytes.
		 * That is to say, before a and B are passed in, they are char type 16 bits, which takes up two bytes, but each time they can only pass in the lower eight bits, so only two bytes are passed in
		 * Because the corresponding codes of upper and lower case letters in the code table are all in the range of byte type, you can pass them in completely without any displacement
		 * Instead, i need to be transferred in completely. i need to be transferred in 4 times. Each time, i need to be transferred in 4 bytes by shaping, but only 1 byte (lower 8 bits) is transferred in each time, so i takes up 4 bytes
		 * The gbk encoding method adopted by the latter Chinese character "Zhong" is that Chinese occupies two bytes and English occupies one byte. So "medium" takes up 2 bytes
		 * So getBytes("gbk") specifies the encoding.
		 * Because the char character takes up 2 bytes in the file's (manual view) encoding mode,
		 * So A takes up 2 bytes, B takes up 2 bytes, i of int class takes up 4 bytes, 2 bytes in total,
		 * So the file length is 12 bytes

		// When reading a file completely, you must start from the file, that is, move the pointer to the header;
		// Read once, store the read contents in byte array

		// raf.length() returns a long type

		// Create a byte array to store the read contents. The length of the array is determined by the length of the file to be read
		byte[] buf = new byte[(int) raf.length()];

		// Read data of up to bytes of array length from the file to the byte array.;

		// Converts the buf array to output as a string using the specified encoding,
		String s1 = new String(buf, "GBK");

		System.out.println(s1);// The output results are disordered
		 * Read it! whole! The file is read out,
		 * i of the int class is divided into four parts,
		 * So the computer can't find the corresponding code, so it's scrambled
		// Output in hex
		for (byte b : buf) {
			System.out.print(Integer.toHexString(b & 0xff) + " ");
		// Close file io stream, be sure!


Topics: Java encoding Oracle