控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt。
方法二:设置一个任意容量的、大小合适的字节缓冲区并且使用来自文件的字节进行填充。然后整理出缓冲区中所有的内容。这种方式的问题是:缓冲区的内容可能会在读取文件的一个数据项时半途而断。这样一来,就必须做一些工作对此进行检测并且找出下一步要做的工作,但是这比第一种方式更加有效,因为这极大减少了用于读取整个文件所需的读操作数目。
本例的关键是缓冲区类提供的compact()方法,即压缩缓冲区。
import java.nio.file.*;
import java.nio.channels.ReadableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer; public class ReadPrimesMixedData2 { public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("primes.txt");
if(!Files.exists(file)) {
System.out.println(file + " does not exist. Terminating program.");
System.exit(1);
} try(ReadableByteChannel inCh = Files.newByteChannel(file)) {
ByteBuffer buf = ByteBuffer.allocateDirect(256);
buf.position(buf.limit()); // Set the position for the loop operation
int strLength = 0; // Stores the string length
byte[] strChars = null; // Array to hold the bytes for the string while(true) {
if(buf.remaining() < 8) { // Verify enough bytes for string length
if(inCh.read(buf.compact()) == -1)
break; // EOF reached
buf.flip();
}
strLength = (int)buf.getDouble(); // Get the string length // Verify enough bytes for complete string
if(buf.remaining() < 2*strLength) {
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the prime string.");
break; // EOF reached
}
buf.flip();
}
strChars = new byte[2*strLength]; // Array for string bytes
buf.get(strChars); // Get the bytes if(buf.remaining() < 8) { // Verify enough bytes for prime value
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the binary prime value.");
break; // EOF reached
}
buf.flip();
} System.out.printf("String length: %3s String: %-12s Binary Value: %3d%n",
strLength, ByteBuffer.wrap(strChars).asCharBuffer(),buf.getLong());
} System.out.println("\nEOF reached."); } catch(IOException e) {
e.printStackTrace();
}
}
}