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

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


下载地址如下:http://www.cnblogs.com/hnrainll/archive/2011/10/11/2206804.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();
		}

	}

}
结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值