JAVA: Random access file is always garbled

This article is based on the possibility that when you use randomAccessFile to read and write a file, you can be sure that the transcoding form is not wrong, but the random code still appears.

package ABC;

import java.io.*;

public class markdown {
	public static void main(String[] argv) {
		try {
			RandomAccessFile br = new RandomAccessFile("D:\\officePC\\onedirve\\OneDrive\\桌面\\1.txt","rw");
			
			String str;
			long position = 0;
			long next_position = 0;
			while((str = br.readLine())!=null) {
				position = br.getFilePointer();
				String str1 = new String(str.getBytes("ISO-8859-1"));
				String str2 = new String("##".getBytes("ISO-8859-1")) + str1;
				br.seek(next_position);
				System.out.println(str2);
				br.write(str2.getBytes());
				br.write(new String("\n").getBytes());
				next_position = position;
			}
			br.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}

After the above code has executed two loops, this situation occurs:

As you can see, I first read a position, position, and then change each line (add). The length of each line changes, but the memory length of each line does not change, so the system sends its extra characters to the next line, and the next line is overwritten.
solution: you must read the rest in and modify it.

Read More: