Java基础之读文件——使用通道读二进制数据(ReadPrimes)

控制台程序,本例读取Java基础之写文件部分(PrimesToFile)写入的primes.bin。

 

 1 import java.nio.file.*;
 2 import java.nio.*;
 3 import java.nio.channels.ReadableByteChannel;
 4 import java.io.IOException;
 5 
 6 public class ReadPrimes {
 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 PRIMECOUNT = 6;
15     final int LONG_BYTES = 8;                                          // Number of bytes for type long
16     ByteBuffer buf = ByteBuffer.allocate(LONG_BYTES*PRIMECOUNT);
17     long[] primes = new long[PRIMECOUNT];
18     try (ReadableByteChannel inCh = Files.newByteChannel(file)){
19       int primesRead = 0;
20       while(inCh.read(buf) != -1) {
21         LongBuffer longBuf = ((ByteBuffer)(buf.flip())).asLongBuffer();
22         primesRead = longBuf.remaining();
23         longBuf.get(primes, 0, primesRead);
24 
25         // List the primes read on the same line
26         System.out.println();
27         for(int i = 0 ; i < primesRead ; ++i) {
28           System.out.printf("%10d", primes[i]);
29         }
30         buf.clear();                                                   // Clear the buffer for the next read
31       }
32       System.out.println("\nEOF reached.");
33     } catch(IOException e) {
34       e.printStackTrace();
35     }
36   }
37 }

 

转载于:https://www.cnblogs.com/mannixiang/p/3387139.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值