OnJava8-Examples/iostreams/UsingRandomAccessFile.java

66 lines
1.5 KiB
Java
Raw Normal View History

2015-11-03 12:00:44 -08:00
// iostreams/UsingRandomAccessFile.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
import java.io.*;
public class UsingRandomAccessFile {
static String file = "rtest.dat";
2017-01-21 12:51:00 -08:00
public static void display() {
try(
RandomAccessFile rf =
new RandomAccessFile(file, "r")
) {
2015-06-15 17:47:35 -07:00
for(int i = 0; i < 7; i++)
System.out.println(
2015-12-15 11:47:04 -08:00
"Value " + i + ": " + rf.readDouble());
2015-06-15 17:47:35 -07:00
System.out.println(rf.readUTF());
2017-01-21 12:51:00 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
2015-06-15 17:47:35 -07:00
}
}
2017-01-21 12:51:00 -08:00
public static void main(String[] args) {
try(
RandomAccessFile rf =
new RandomAccessFile(file, "rw")
) {
2015-12-15 11:47:04 -08:00
for(int i = 0; i < 7; i++)
rf.writeDouble(i*1.414);
rf.writeUTF("The end of the file");
rf.close();
display();
2017-01-21 12:51:00 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
2015-12-15 11:47:04 -08:00
}
try(
RandomAccessFile rf =
new RandomAccessFile(file, "rw")
) {
2015-12-15 11:47:04 -08:00
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
display();
2017-01-21 12:51:00 -08:00
} catch(IOException e) {
throw new RuntimeException(e);
2015-12-15 11:47:04 -08:00
}
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
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
2015-09-07 11:44:36 -06:00
*/