控制台程序,将一系列有用的格言写入到文件中。
本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前字符串中存在的字符数目,也可以使用视图缓冲区来读取字符串。
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 WriteProverbs { 10 public static void main(String[] args) { 11 String[] sayings = { 12 "Indecision maximizes flexibility.", 13 "Only the mediocre are always at their best.", 14 "A little knowledge is a dangerous thing.", 15 "Many a mickle makes a muckle.", 16 "Who begins too much achieves little.", 17 "Who knows most says least.", 18 "A wise man sits on the hole in his carpet." 19 }; 20 21 Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("Proverbs.txt");// Path object for the file 22 try { 23 Files.createDirectories(file.getParent()); // Make sure we have the directory 24 } catch (IOException e) { 25 e.printStackTrace(); 26 System.exit(1); 27 } 28 29 // The buffer must accommodate the longest string 30 // so we find the length of the longest string 31 int maxLength = 0; 32 for (String saying : sayings) { 33 if(maxLength < saying.length()) 34 maxLength = saying.length(); 35 } 36 // The buffer length must hold the longest string 37 // plus its length as a binary integer 38 // Each character needs 2 bytes and an integer 4 bytes 39 ByteBuffer buf = ByteBuffer.allocate(2*maxLength + 4); 40 41 try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE, APPEND))) { 42 43 for (String saying : sayings) { 44 buf.putInt(saying.length()).asCharBuffer().put(saying); 45 buf.position(buf.position() + 2*saying.length()).flip(); 46 channel.write(buf); // Write the buffer to the file channel 47 buf.clear(); 48 } 49 System.out.println("Proverbs written to file."); 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 } 54 }