Java基础之写文件——将多个字符串写入到文件中(WriteProverbs)

控制台程序,将一系列有用的格言写入到文件中。

本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前字符串中存在的字符数目,也可以使用视图缓冲区来读取字符串。

 import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*; import java.util.EnumSet;
import java.io.IOException;
import java.nio.ByteBuffer; public class WriteProverbs {
public static void main(String[] args) {
String[] sayings = {
"Indecision maximizes flexibility.",
"Only the mediocre are always at their best.",
"A little knowledge is a dangerous thing.",
"Many a mickle makes a muckle.",
"Who begins too much achieves little.",
"Who knows most says least.",
"A wise man sits on the hole in his carpet."
}; Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("Proverbs.txt");// Path object for the file
try {
Files.createDirectories(file.getParent()); // Make sure we have the directory
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} // The buffer must accommodate the longest string
// so we find the length of the longest string
int maxLength = 0;
for (String saying : sayings) {
if(maxLength < saying.length())
maxLength = saying.length();
}
// The buffer length must hold the longest string
// plus its length as a binary integer
// Each character needs 2 bytes and an integer 4 bytes
ByteBuffer buf = ByteBuffer.allocate(2*maxLength + 4); try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE, APPEND))) { for (String saying : sayings) {
buf.putInt(saying.length()).asCharBuffer().put(saying);
buf.position(buf.position() + 2*saying.length()).flip();
channel.write(buf); // Write the buffer to the file channel
buf.clear();
}
System.out.println("Proverbs written to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上一篇:欢迎关注我的微信公众账号:Linux技巧(微信号:irefactoring),一起学习Linux知识~~~


下一篇:Codeforces Round #385 (Div. 2) B - Hongcow Solves A Puzzle 暴力