控制台程序,使用Formatter对象将写入文件的数据准备好。

使用Formatter对象的format()方法,将数据值格式化到视图缓冲区charBuf中。

 import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*; // Files and Path
import java.nio.channels.WritableByteChannel;
import java.nio.*; // ByteBuffer and CharBuffer
import java.util.*; // Formatter and EnumSet
import java.io.IOException; public class UsingAFormatter {
public static void main(String[] args) {
String[] phrases = {"Rome wasn't burned in a day.",
"It's a bold mouse that sits in the cat's ear.",
"An ounce of practice is worth a pound of instruction."
};
String separator = System.lineSeparator(); // Get line separator
Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("Phrases.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);
} try (WritableByteChannel channel = Files.newByteChannel(file, EnumSet.of(WRITE, CREATE, APPEND))) { ByteBuffer buf = ByteBuffer.allocate(1024);
CharBuffer charBuf = buf.asCharBuffer(); // Create a view buffer
System.out.println("Char view buffer:");
System.out.printf("position = %2d Limit = %4d capacity = %4d%n", charBuf.position(),charBuf.limit(),charBuf.capacity()); Formatter formatter = new Formatter(charBuf); // Write to the view buffer using a formatter
int number = 0; // Proverb number
for(String phrase : phrases) {
formatter.format("Proverb%2d: %s%s", ++number, phrase, separator);
System.out.println("\nView buffer after loading:");
System.out.printf("position = %2d Limit = %4d capacity = %4d%n", charBuf.position(), charBuf.limit(),charBuf.capacity()); charBuf.flip(); // Flip the view buffer
System.out.println("View buffer after flip:");
System.out.printf("position = %2d Limit = %4d length = %4d%n", charBuf.position(),charBuf.limit(),charBuf.length()); buf.limit(2*charBuf.length()); // Set byte buffer limit System.out.println("Byte buffer after limit update:");
System.out.printf("position = %2d Limit = %4d length = %4d%n", buf.position(),buf.limit(), buf.remaining()); channel.write(buf); // Write buffer to the channel
System.out.println("Buffer contents written to file.");
buf.clear();
charBuf.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java基础之写文件——使用Formatter对象加载缓冲区(UsingAFormatter)的更多相关文章

  1. Java基础之写文件——从多个缓冲区写(GatheringWrite)

    控制台程序,使用单个写操作将数据从多个缓冲区按顺序传输到文件,这称为集中写(GatheringWrite)操作.这个功能的优势是能够避免在将信息写入到文件中之前将信息复制到单个缓冲区中.从每个缓冲区写 ...

  2. Java基础之写文件——将素数写入文件中(PrimesToFile)

    控制台程序,计算素数.创建文件路径.写文件. import static java.lang.Math.ceil; import static java.lang.Math.sqrt; import ...

  3. Java基础之写文件——缓冲区中的多条记录(PrimesToFile3)

    控制台程序,上一条博文(PrimesToFile2)每次将一个素数写入到文件中,所以效率不是很高.最好是使用更大的缓冲区并加载多个素数. 本例重复使用三个不同的视图缓冲区加载字节缓冲区并尽可能加入更多 ...

  4. Java基础6:代码块与代码加载顺序

    更多内容请关注微信公众号[Java技术江湖] 这是一位阿里 Java 工程师的技术小站,作者黄小斜,专注 Java 相关技术:SSM.SpringBoot.MySQL.分布式.中间件.集群.Linux ...

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

    控制台程序,将一系列有用的格言写入到文件中. 本例使用通道把不同长度的字符串写入到文件中,为了方便从文件中恢复字符串,将每个字符串的长度写入到文件中紧靠字符串本身前面的位置,这可以告知在读取字符串之前 ...

  6. Java基础之写文件——在通道写入过程中的缓冲区状态(BufferStateTrace)

    控制台程序,在Junk目录中将字符串“Garbage in, garbage out\n”写入到名为charData.txt的文件中. import static java.nio.file.Stan ...

  7. Java基础之写文件——使用带缓冲的Writer写文件(WriterOutputToFile)

    控制台程序,将一列字符串写入到文件中. import java.io.*; import java.nio.file.*; import java.nio.charset.Charset; publi ...

  8. Java基础之写文件——创建通道并且写文件(TryChannel)

    控制台程序,创建一个文件并且使用通道将一些文本写入到这个文件中. import static java.nio.file.StandardOpenOption.*; import java.nio.c ...

  9. Java基础之写文件——通过缓冲流写文件(StreamOutputToFile)

    控制台程序,生成一些二进制整型值并且将它们写入到文件中. import java.nio.file.*; import java.nio.*; import java.io.*; public cla ...

随机推荐

  1. django 1.8 日志配置

    django 1.8 日志配置 以下为setings配置logging代码片段 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(_ ...

  2. UIButton的遍历

    for (id obj in self.view.subviews) {                if ([obj isKindOfClass:[UIButton class]]) {      ...

  3. /etc/hosts.conf

    一 作用       指定如何解析主机域名.可设置网络安全. 二 参数说明      默认情况,/etc/hosts.conf 文件有如下内容——      order hosts,bind     ...

  4. 1 2 3 n

    n(n+1)/2 连续自然数 1,2,3.....,n 队列 从中任意取出1至n个相加,可以表示的连续自然数队列中最大的自然数是多少 受"高斯求和--蛇头蛇尾脑图--长方形对角线脑图--苯环 ...

  5. 【php学习】字符串操作

    关于字符串的处理,基本上就是那几种操作:字符串长度.查找子字符串的位置.替换字符串.截取字符串.拆分合并字符串 ... 字符串的定义:直接 $str = "abcd"; 或者 $s ...

  6. 基于java工程开发RMI服务端

    ServiceRegist.java import java.rmi.Remote; import java.rmi.RemoteException; public interface Service ...

  7. [daily][optimize] 一个小python程序的性能优化 (python类型转换函数引申的性能优化)

    前天,20161012,到望京面试.第四个职位,终于进了二面.好么,结果人力安排完了面试时间竟然没有通知我,也没有收到短信邀请.如果没有短信邀请门口的保安大哥是不让我进去大厦的.然后,我在11号接到了 ...

  8. npm的使用

    npm的用途: 用官方的包 用其他人的包 传自己的包给别人用 一: 安装 1.用别人的: npm install argv 这样下载好之后,argv包就放在了工程目录下的node_modules目录中 ...

  9. Xcode --自动注释插件VVDocumenter-Xcode(配置须知)

    VVDocumenter-Xcode 是由 @onevcat 喵神开发的一个Xcode插件,其作用是在Xcode中输入"///"后自动生成规范的文档注释,的确非常好用而且实用. 百 ...

  10. Using Change Management and Change Control Within a Project

    In any project, change is inevitable whether it comes from within the project or from external sourc ...