Use a random access file

From CodeCodex

Revision as of 17:20, 28 July 2010 by 211.2.129.92 (Talk)

Implementations

Java

    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) {
    }

Ruby

filename = "/work/temp.txt"
open(filename, "r+") do |fp|
  chr = File.read(fp,1)         # Read a character
  fp.seek(0, IO::SEEK_END)      # Seek to end of file
  fp.write("aString")           # Append to the end
  fp.seek(0)                    # Seek to start of file
  fp.write("test")              # Overwriting of the file
end