The main function of the Randomaccessfile class is to complete the random read function to read the content at the specified location. Responsible for manipulating the contents of the file.
Construction Method:
Public Randomaccessfile (File file,string mode)
When instantiating this class, you pass a file class that tells the system which file to manipulate, followed by an open mode for the files:
- R: Read-only
- W: Write only
- RW: Read and write, if this mode is used, the file does not exist and is automatically created
Write operations
Package Lianxijihe;import Java.io.file;import Java.io.filenotfoundexception;import java.io.ioexception;import Java.io.randomaccessfile;public class lianxi042 {public static void main (string[] args) {file F = new File ("F:\\abc.txt"); try {randomaccessfile RDF = new Randomaccessfile (f, "RW"); String name = "FFFFFFFF"; int age =30;rdf.writebytes (name); Rdf.writeint (+); Rdf.close (); catch (FileNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();}}}
Read operation
Package Lianxijihe;import Java.io.file;import Java.io.filenotfoundexception;import java.io.ioexception;import Java.io.randomaccessfile;public class lianxi042 {public static void main (string[] args) {file F = new File ("F:\\abc.txt"); try {randomaccessfile RDF = new Randomaccessfile (f, "RW"); String name = ""; int age =0;byte b[] = new byte[8];for (int i=0;i<b.length;i++) {B[i] = Rdf.readbyte ();} name = new String (b); age = Rdf.readint (); SYSTEM.OUT.PRINTLN (name); System.out.println (age); Rdf.close ();} catch (FileNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();}}}