OnJava8-Examples/iostreams/UsingRandomAccessFile.java
2015-12-15 11:47:04 -08:00

55 lines
1.3 KiB
Java

// iostreams/UsingRandomAccessFile.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
import java.io.*;
public class UsingRandomAccessFile {
static String file = "rtest.dat";
static void display() throws IOException {
try(RandomAccessFile rf =
new RandomAccessFile(file, "r")) {
for(int i = 0; i < 7; i++)
System.out.println(
"Value " + i + ": " + rf.readDouble());
System.out.println(rf.readUTF());
}
}
public static
void main(String[] args) throws IOException {
try(RandomAccessFile rf =
new RandomAccessFile(file, "rw")) {
for(int i = 0; i < 7; i++)
rf.writeDouble(i*1.414);
rf.writeUTF("The end of the file");
rf.close();
display();
}
try(RandomAccessFile rf =
new RandomAccessFile(file, "rw")) {
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
display();
}
}
}
/* Output:
Value 0: 0.0
Value 1: 1.414
Value 2: 2.828
Value 3: 4.242
Value 4: 5.656
Value 5: 7.069999999999999
Value 6: 8.484
The end of the file
Value 0: 0.0
Value 1: 1.414
Value 2: 2.828
Value 3: 4.242
Value 4: 5.656
Value 5: 47.0001
Value 6: 8.484
The end of the file
*/