控制台程序,使用通道随机读写primes_backup.bin文件。
1 import static java.nio.file.StandardOpenOption.*; 2 import java.nio.file.*; 3 import java.nio.channels.SeekableByteChannel; 4 import java.io.IOException; 5 import java.nio.ByteBuffer; 6 import java.util.EnumSet; 7 8 public class RandomReadWrite { 9 public static void main(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 position 46 buf.flip(); // Flip the buffer 47 primes[i] = buf.getLong(); // Extract the prime 48 if(primes[i] != REPLACEMENT) { 49 break; // It's good so exit the inner loop 50 } else { 51 buf.clear(); // Clear ready to read another 52 } 53 } 54 buf.flip(); // Flip to ready for insertion 55 buf.putLong(REPLACEMENT); // Replacement into buffer 56 buf.flip(); // Flip ready to write 57 channel.position(index).write(buf); // Write the replacement to file 58 buf.clear(); // Reset ready for next read 59 }*/ 60 61 int count = 0; // Count of primes written 62 for(long prime : 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 }