java nio学习笔记<一>
package nio;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.channels.FileChannel;import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;/** * 关于NIO的其他内容可以参考:http://www.iteye.com/topic/834447 * @author Administrator * */public class ChannelDemo1 {public static void main(String[] args) throws IOException {// writeFile("c:\\aaaa.txt");// readFile("c:\\aaaa.txt");// readFileByReader("c:\\aaaa.txt");copy("c:\\aaaa.txt", "c:\\aaaa2.txt");}public static void writeFile(String fileName) throws IOException {/* * Channel是一个对象(通道),可以通过它读取或写入数据。拿NIO和IO相比较通道就像是流。 * 所有的数据都是通过Buffer来处理,您永远不会将字节直接写入通道中,而是将数据写入缓冲区,读取的话也是将数据读取到缓冲区。 */FileChannel fileOutChannel = (new FileOutputStream(fileName, true)).getChannel();// 将经过UTF-8编码的字符写入到buffer中,然后通道负责把buffer写入到输出流。fileOutChannel.write(Charset.forName("utf-8").encode(CharBuffer.wrap("北京 您好!\n")));fileOutChannel.close();}/* * 指定InputStreamReader的解析字符集读取文件 */public static void readFileByReader(String fileName) throws IOException {BufferedReader buff = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.forName("utf-8")));String s;while ((s = buff.readLine()) != null) {System.out.println(s);}buff.close();}// nio读取文件public static void readFile(String fileName) throws IOException {FileChannel fileInChannel = (new FileInputStream(fileName)).getChannel();Charset charset = Charset.forName("UTF-8");CharsetDecoder decoder = charset.newDecoder();// CharsetEncoder encoder = charset.newEncoder();/* * allocateDirect:直接缓冲区,allocate非直接缓冲区, 直接缓冲区是一块连续的内存区域,适合长期驻留内存的数据, * 非直接缓冲区适合相当于一次性的,适合用完就扔。 */ByteBuffer buff = ByteBuffer.allocateDirect(1024);CharBuffer charBuff = CharBuffer.allocate(1024);while (fileInChannel.read(buff) != -1) {// flip用于反转buff.flip();// 将字节数组转换成字符数组decoder.decode(buff, charBuff, false);charBuff.flip();System.out.println("read:" + charBuff);buff.clear();charBuff.clear();}fileInChannel.close();// 下面代码证明关闭FileChannel也完全关闭了文件句柄FileChannel fileInChannel11 = (new FileInputStream(fileName)).getChannel();System.out.println(fileInChannel11.isOpen());fileInChannel11.close();System.out.println(fileInChannel11.isOpen());}// nio copy文件public static void copy(String src, String dest) throws IOException {FileChannel srcChannel = (new FileInputStream(src)).getChannel();FileChannel destChannel = (new FileOutputStream(dest)).getChannel();ByteBuffer buff = ByteBuffer.allocate(1024);while (true) {//清空缓冲区,使其可以接受数据buff.clear();if (srcChannel.read(buff) == -1) {break;}//将数据读取到缓冲区后,如果要把缓冲区的数据写到通道就要先反转buff.flip();destChannel.write(buff);}srcChannel.close();destChannel.close();}}