您的位置:首页 > 编程语言 > Java开发

Java学习笔记——通道写文件与帮助文档

2014-12-06 10:35 369 查看
Java的API文档可以很好地向我们展示函数或类的定义和结构层次,让我们可以很好地看懂之前没用过的类或函数,如下图所示,但没有搜索功能,只能根据函数的出处来寻找。



下载地址如下:/article/6959322.html

通道的具体实现如下:

import static java.nio.file.StandardOpenOption.*;
import java.nio.channels.WritableByteChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.nio.file.*;

public class TryChannel {

/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
String[] sayings = { "Teacher: Kids,what does the chicken give you?",
"Student: Meat!",
"Teacher: Very good! Now what does the pig give you?",
"Student: Bacon!",
" Teacher: Great! And what does the fat cow give you?",
"Student: Homework!" };
String separator = System.lineSeparator();//设定分割符
Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Stuff").resolve("Moresayings.txt");
try {
Files.createDirectories(file.getParent());

} catch (IOException e) {
System.err.println("Error creating directory:" + file.getParent());
e.printStackTrace();
System.exit(1);

}
System.out.println("New file is:" + file);
ByteBuffer buf = null;
try {
WritableByteChannel channel = Files.newByteChannel(file, EnumSet
.of(CREATE, WRITE));//创建写通道,第一个参数是要写入的位置,第二个是通道打开的方式
for (String saying : sayings) {
buf = ByteBuffer.wrap((saying + separator).getBytes());//warp是将字符串包裹成缓冲池形式
channel.write(buf);
}
System.out.println("File written");

} catch (IOException e) {
e.printStackTrace();
}

}

}
结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: