读书人

NIO学习小结

发布时间: 2012-08-24 10:00:21 作者: rapoo

NIO学习总结

/**   * 使用传统的I/O读取文件内容  * @param filePath  文件路径   * @throws IOException*/ public static void ioRead(String filePath) throws IOException {        File file = new File(filePath);        FileInputStream fis = new FileInputStream(file);        byte[] b = new byte[1024];        fis.read(b);        System.out.println(new String(b)); }/**  * 使用NIO读取文件内容  * @param filePath 文件路径  * @throws IOException*/  public static void nioRead(String filePath) throws IOException {        File file = new File(filePath);        FileInputStream fis = new FileInputStream(file);        FileChannel channel = fis.getChannel();        ByteBuffer b = ByteBuffer.allocate(1024);        channel.read(b);        byte[] by = b.array();        System.out.println(new String(by));  }/**  * 传统I/O写文件  *   * @param filePath  文件路径  * @throws IOException*/  public static void ioWrite(String filePath) throws IOException   {        File file = new File(filePath);        FileOutputStream fos = new FileOutputStream(file);        String[] contents = new String[] { "qian", "hao" };        for (String content : contents)         {   byte[] b = content.getBytes(Charset.forName("UTF-8"));   fos.write(b);        }   }/**  * NIO写文件  * @param filePath 文件路径  * @throws IOException*/ public static void nioWrite(String filePath) throws IOException {        File file = new File(filePath);        FileOutputStream fos = new FileOutputStream(file);        // 获取文件通道         FileChannel channel = fos.getChannel();        // 设置文件缓冲区         ByteBuffer buffer = ByteBuffer.allocate(1024);        String[] contents = new String[] { "qian", "hao" };        // 将数据读入缓冲区中         for (String content : contents)        {  buffer.put(content.getBytes());       }       // 通道反转(将读通道转化为写通道)  buffer.flip();       // 将文件写入写通道中  channel.write(buffer); }/**  * 将一个文件内容复制到另外一个文件中  * @param resource  源文件路径  * @param destination 目标文件路径  * @throws IOException*/ public static void nioCopyFile(String resource, String destination)throws IOException {       // 设置文件输入流        FileInputStream fis = new FileInputStream(resource);       // 设置文件输出流        FileOutputStream fos = new FileOutputStream(destination);       // 设置输入通道        FileChannel readChannel = fis.getChannel();       // 设置输出通道        FileChannel writeChannel = fos.getChannel();       // 创建缓冲区        ByteBuffer buffer = ByteBuffer.allocate(1024);       // 复制文件        while (true)        {        // 清空缓冲,使其接受新的数据buffer.clear();        // 从输入通道中将数据写入缓冲区中int len = readChannel.read(buffer);        // 判断是否文件已读取完成if (len == -1)          {   break;}        // 将缓冲区的数据些到另外一个通道,(输入通道反转到输出通道)   buffer.flip();        // 从输出通道将数据写到缓冲区,写入文件中   writeChannel.write(buffer);} }

读书人网 >编程

热点推荐