控制台程序,在Junk目录中将字符串“Garbage in, garbage out ”写入到名为charData.txt的文件中。
1 import static java.nio.file.StandardOpenOption.*; 2 import java.nio.file.*; 3 import java.nio.channels.*; 4 5 import java.util.EnumSet; 6 import java.io.IOException; 7 import java.nio.ByteBuffer; 8 9 public class BufferStateTrace { 10 public static void main(String[] args) { 11 String phrase = "Garbage in, garbage out. "; 12 13 Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("charData.txt"); // Path object for the file 14 try { 15 Files.createDirectories(file.getParent()); // Make sure we have the directory 16 } catch (IOException e) { 17 e.printStackTrace(); 18 System.exit(1); 19 } 20 21 try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE, APPEND))) { 22 ByteBuffer buf = ByteBuffer.allocate(1024); 23 System.out.printf( 24 " New buffer: position = %1$2d Limit = %2$4d capacity = %3$4d", 25 buf.position(), buf.limit(), buf.capacity()); 26 // Load the data into the buffer 27 for(char ch : phrase.toCharArray()) 28 buf.putChar(ch); 29 System.out.printf( 30 " Buffer after loading: position = %1$2d Limit = %2$4d capacity = %3$4d", 31 buf.position(), buf.limit(), buf.capacity()); 32 buf.flip(); // Flip the buffer ready for file write 33 System.out.printf( 34 " Buffer after flip: position = %1$2d Limit = %2$4d capacity = %3$4d", 35 buf.position(), buf.limit(), buf.capacity()); 36 channel.write(buf); // Write the buffer to the file channel 37 38 // Uncomment the following to get the size of the file in the output 39 // System.out.println(" The file contains " + ((FileChannel)channel).size() + " bytes."); 40 41 buf.flip(); 42 channel.write(buf); // Write the buffer again to the file channel 43 System.out.println(" Buffer contents written to the file."); 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } 47 } 48 }