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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值