控制台程序,使用通道从缓冲区获取数据,读取Java基础之写文件(BufferStateTrace)写入的charData.txt
1 import java.nio.file.*; 2 import java.nio.channels.ReadableByteChannel; 3 import java.io.IOException; 4 import java.nio.ByteBuffer; 5 6 public class ReadAString { 7 8 public static void main(String[] args) { 9 10 Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("charData.txt"); 11 if(!Files.exists(file)) { 12 System.out.println(file + " does not exist. Terminating program."); 13 System.exit(1);; 14 } 15 16 ByteBuffer buf = ByteBuffer.allocate(50); 17 try (ReadableByteChannel inCh = Files.newByteChannel(file)){ 18 while(inCh.read(buf) != -1) { 19 System.out.print("String read: " + 20 ((ByteBuffer)(buf.flip())).asCharBuffer().toString()); 21 buf.clear(); // Clear the buffer for the next read 22 } 23 System.out.println("EOF reached."); 24 } catch(IOException e) { 25 e.printStackTrace(); 26 } 27 } 28 }