控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt。
方法一:可以在第一个读操作中读取字符串的长度,然后再将字符串和二进制素数值读入到文本中。这种方式的唯一不足是:这不是一种有效读取文件的方式,因为有很多的读操作,其中的每个都读取非常少量的数据。
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 ReadPrimesMixedData { 7 public static void main(String[] args) { 8 Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes.txt"); 9 if(!Files.exists(file)) { 10 System.out.println(file + " does not exist. Terminating program."); 11 System.exit(1);; 12 } 13 14 try (FileChannel inCh = (FileChannel)Files.newByteChannel(file)){ 15 ByteBuffer lengthBuf = ByteBuffer.allocate(8); 16 int strLength = 0; // Stores the string length 17 18 ByteBuffer[] buffers = { 19 null, // Byte buffer to hold string 20 ByteBuffer.allocate(8) // Byte buffer to hold prime 21 }; 22 23 while(true) { 24 if(inCh.read(lengthBuf) == -1) // Read the string length, 25 break; // if its EOF exit the loop 26 27 lengthBuf.flip(); 28 29 // Extract the length and convert to int 30 strLength = (int)lengthBuf.getDouble(); 31 32 // Now create the buffer for the string 33 buffers[0] = ByteBuffer.allocate(2*strLength); 34 35 if(inCh.read(buffers) == -1) { // Read the string & binary prime value 36 // Should not get here! 37 System.err.println("EOF found reading the prime string."); 38 break; // Exit loop on EOF 39 } 40 41 System.out.printf( 42 "String length: %3s String: %-12s Binary Value: %3d%n", 43 strLength, 44 ((ByteBuffer)(buffers[0].flip())).asCharBuffer().toString(), 45 ((ByteBuffer)buffers[1].flip()).getLong()); 46 47 // Clear the buffers for the next read 48 lengthBuf.clear(); 49 buffers[1].clear(); 50 } 51 System.out.println(" EOF reached."); 52 } catch(IOException e) { 53 e.printStackTrace(); 54 } 55 } 56 }