Using a Random Access File

try { File f = new File("filename"); RandomAccessFile raf = new RandomAccessFile(f, "rw"); // Read a character char ch = raf.readChar(); // Seek to end of file raf.seek(f.length()); // Append to the end raf.writeChars("aString"); raf.close(); } catch (IOException e) { }

Comments

12 Jan 2010 - 8:03pm by Anonymous (not verified)

i want more example about using RandomAccessFile!!!!!!

22 Feb 2010 - 5:26am by Anonymous (not verified)
import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; /** * * @author javadb.com */ public class Main { /** * Example method for using the RandomAccessFile class */ public void testRandomAccessFile(String filename) { RandomAccessFile randomAccessFile = null; try { //Declare variables that we're going to write String line1 = "First line\n"; String line2 = "Second line\n"; //Create RandomAccessFile instance with read / write permissions randomAccessFile = new RandomAccessFile(filename, "rw"); //Write two lines to the file randomAccessFile.writeBytes(line1); randomAccessFile.writeBytes(line2); //Place the file pointer at the end of the first line randomAccessFile.seek(line1.length()); //Declare a buffer with the same length as the second line byte[] buffer = new byte[line2.length()]; //Read data from the file randomAccessFile.read(buffer); //Print out the buffer contents System.out.println(new String(buffer)); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (randomAccessFile != null) randomAccessFile.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().testRandomAccessFile("myFile.txt"); } }
11 Mar 2010 - 11:56am by Anonymous (not verified)

bien

11 Mar 2010 - 11:56am by Anonymous (not verified)

bien

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.