Java基础之读文件——使用通道随机读取文件(RandomFileRead)

 1 import java.nio.file.*;
 2 import java.nio.channels.FileChannel;
 3 import java.io.IOException;
 4 import java.nio.ByteBuffer;
 5 
 6 public class RandomFileRead {
 7   public static void main(String[] args) {
 8     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes.bin");
 9     if(!Files.exists(file)) {
10       System.out.println(file + " does not exist. Terminating program.");
11       System.exit(1);
12     }
13 
14     final int PRIMESREQUIRED = 10;
15       final int LONG_BYTES = 8;                                        // Number of bytes for type long
16     ByteBuffer buf = ByteBuffer.allocate(LONG_BYTES*PRIMESREQUIRED);
17 
18     long[] primes = new long[PRIMESREQUIRED];
19     int index = 0;                                                     // Position for a prime in the file
20 
21     try (FileChannel inCh = (FileChannel)(Files.newByteChannel(file))){
22       // Count of primes in the file
23       final int PRIMECOUNT = (int)inCh.size()/LONG_BYTES;
24 
25       // Read the number of random primes required
26       for(int i = 0 ; i < PRIMESREQUIRED ; ++i) {
27         index = LONG_BYTES*(int)(PRIMECOUNT*Math.random());
28         inCh.read(buf, index);                                         // Read the value
29             //    inCh.position(index).read(buf);                      // Read the value
30         buf.flip();
31         primes[i] = buf.getLong();                                     // Save it in the array
32         buf.clear();
33       }
34 
35       // Output the selection of random primes 5 to a line in field width of 12
36       int count = 0;                                                   // Count of primes written
37       for(long prime : primes) {
38         System.out.printf("%12d", prime);
39         if(++count%5 == 0) {
40           System.out.println();
41         }
42       }
43 
44     } catch(IOException e) {
45       e.printStackTrace();
46     }
47   }
48 }

控制塔程序,本例从primes.bin文件中随机选择一些值进行提取。

原文地址:https://www.cnblogs.com/mannixiang/p/3407672.html