Difference between revisions of "Use a random access file"

From CodeCodex

(Ruby)
Line 17: Line 17:
 
     } catch (IOException e) {
 
     } catch (IOException e) {
 
     }
 
     }
 +
</pre>
 +
 +
===Ruby===
 +
<pre>
 +
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
 
</pre>
 
</pre>
  
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Ruby]]
 
[[Category:I/O]]
 
[[Category:I/O]]

Revision as of 17:20, 28 July 2010

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