1 import static java.nio.file.StandardOpenOption.*;2 import java.nio.file.*;3 importjava.nio.channels.SeekableByteChannel;4 importjava.io.IOException;5 importjava.nio.ByteBuffer;6 importjava.util.EnumSet;7
8 public classRandomReadWrite {9 public static voidmain(String[] args)10 {11 Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes_backup.bin");12 if(!Files.exists(file)) {13 System.out.println(file + " does not exist. Terminating program.");14 System.exit(1);15 }16
17 final int PRIMESREQUIRED = 10;18 ByteBuffer buf = ByteBuffer.allocate(8);19
20 long[] primes = new long[PRIMESREQUIRED];21 int index = 0; //Position for a prime in the file
22 final long REPLACEMENT = 99999L; //Replacement for a selected prime
23
24 try (SeekableByteChannel channel =Files.newByteChannel(file, EnumSet.of(READ, WRITE))){25 final int PRIMECOUNT = (int)channel.size()/8;26 System.out.println("Prime count = "+PRIMECOUNT);27 for(int i = 0 ; i < PRIMESREQUIRED ; ++i) {28 index = 8*(int)(PRIMECOUNT*Math.random());29 channel.position(index).read(buf); //Read at a random position
30 buf.flip(); //Flip the buffer
31 primes[i] = buf.getLong(); //Extract the prime
32 buf.flip(); //Flip to ready for insertion
33 buf.putLong(REPLACEMENT); //Replacement into buffer
34 buf.flip(); //Flip ready to write
35 channel.position(index).write(buf); //Write the replacement to file
36 buf.clear(); //Reset ready for next read
37 }38
39 //Alternate loop code to avoid selecting REPLACEMENT values
40 /*for(int i = 0 ; i < PRIMESREQUIRED ; ++i)41 {42 while(true)43 {44 index = 8*(int)(PRIMECOUNT*Math.random());45 channel.position(index).read(buf); // Read at a random position46 buf.flip(); // Flip the buffer47 primes[i] = buf.getLong(); // Extract the prime48 if(primes[i] != REPLACEMENT) {49 break; // It's good so exit the inner loop50 } else {51 buf.clear(); // Clear ready to read another52 }53 }54 buf.flip(); // Flip to ready for insertion55 buf.putLong(REPLACEMENT); // Replacement into buffer56 buf.flip(); // Flip ready to write57 channel.position(index).write(buf); // Write the replacement to file58 buf.clear(); // Reset ready for next read59 }*/
60
61 int count = 0; //Count of primes written
62 for(longprime : primes) {63 System.out.printf("%12d", prime);64 if(++count%5 == 0) {65 System.out.println();66 }67 }68 } catch(IOException e) {69 e.printStackTrace();70 }71 }72 }