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

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

 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();
}
}
}

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

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

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

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

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

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

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

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

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

  5. Java基础(一):I/O多路复用模型及Linux中的应用

    IO多路复用模型广泛的应用于各种高并发的中间件中,那么区别于其他模式他的优势是什么.其核心设计思想又是什么.其在Linux中是如何实现的? I/O模型 I/O模型主要有以下五种: 同步阻塞I/O:I/ ...

  6. 字符串写入txt文件

    将字符串写入C盘txt文件里 File.AppendAllText(@"C:\" + DateTime.Now.ToString("HHmmss") + &qu ...

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

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

  8. Java基础之写文件——使用Formatter对象加载缓冲区(UsingAFormatter)

    控制台程序,使用Formatter对象将写入文件的数据准备好. 使用Formatter对象的format()方法,将数据值格式化到视图缓冲区charBuf中. import static java.n ...

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

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

随机推荐

  1. UIButton的遍历

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

  2. 解决Windows照片查看器中图片显示发黄的问题

    这其实是ICC颜色配置的问题,发生在Windows7自动更新下载了显示器的驱动后,自动安装后显示器的颜色配额制文件自动改为新下载的配置,导致显卡和显示器颜色配置不兼容的问题,不过不用担心,非常容易解决 ...

  3. 同IP不同端口Session冲突问题

    同IP不同端口Session冲突问题 分类: tomcat2013-09-24 11:19 1146人阅读 评论(0) 收藏 举报 一个服务器上搭建了多个tomcat或者weblogic,端口不一样, ...

  4. Unity 父物体与子物体位置

         酷跑片段本来想做三条轨道,然后通过切换轨道来做,后面发现一种巧妙的方法,利用物体的父级偏移来实现轨道的切换. 比如上图,实际运动的是Car对象,通过修改MineControler的左右位置( ...

  5. VPN服务器环境搭建

    一.VPN服务器环境说明 操作系统:CentOS release 6.4 (Final) 本地网卡: 复制代码 代码如下: # ifconfig em1 Link encap:Ethernet HWa ...

  6. Why Apache Beam? A data Artisans perspective

    https://cloud.google.com/dataflow/blog/dataflow-beam-and-spark-comparison https://github.com/apache/ ...

  7. (转)freemakeer初入门

    在web开发过程中,尤其是后台管理系统的开发中,少不了增删改成的基础操作,原来我自己的做法是一份一份的拷贝粘贴,然后修改其中的不同,然而这样既枯燥无味又浪费了大量的时间,所以根据自己项目结构的特点写了 ...

  8. boost.compressed_pair源码剖析

    意义 当compressed_pair的某一个模板参数为一个空类的时候将对其进行“空基类优化”,这样可以使得compressed_pair占用的空间比std::pair的更小. 参考如下代码: #in ...

  9. Which Python memory profiler is recommended

    http://stackoverflow.com/questions/110259/which-Python-memory-profiler-is-recommended/110826#110826

  10. eigen主页

    http://eigen.tuxfamily.org/index.php?title=Main_Page