控制台程序,本例读取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(" EOF reached."); 33 } catch(IOException e) { 34 e.printStackTrace(); 35 } 36 } 37 }