利用FileChannel完成文件的读、写、复制

内容:通过NIO中的FileChannel完成文件的读、写、复制。

[java]  view plain  copy
  1. public class NioFileCopy {  
  2.     private RandomAccessFile aFile = null;  
  3.     private FileChannel inChannel = null;  
  4.     private final ByteBuffer buf = ByteBuffer.allocate(1024);  
  5.       
  6.     public void doWrite() throws IOException {  
  7.         aFile = new RandomAccessFile("C:/goods.txt""rw");  
  8.         inChannel = aFile.getChannel();  
  9.         String newData = "New String to wirte to file... " + System.currentTimeMillis();  
  10.         buf.clear();  
  11.         buf.put(newData.getBytes());  
  12.           
  13.         buf.flip();  
  14.           
  15.         while (buf.hasRemaining())   
  16.             inChannel.write(buf);  
  17.           
  18.         inChannel.close();  
  19.         System.out.println("Write Over");  
  20.     }  
  21.       
  22.     public void doRead() throws IOException {  
  23.         aFile = new RandomAccessFile("C:/goods.txt""rw");  
  24.         inChannel = aFile.getChannel();  
  25.           
  26.         int bytesRead = inChannel.read(buf);  
  27.         while (bytesRead != -1) {  
  28.             System.out.println("Read " + bytesRead);  
  29.             buf.flip();  
  30.             while (buf.hasRemaining())  
  31.                 System.out.print((char) buf.get());  
  32.               
  33.             buf.clear();  
  34.             bytesRead = inChannel.read(buf);  
  35.         }  
  36.           
  37.         aFile.close();  
  38.     }  
  39.       
  40.     public void doCopy() throws IOException {  
  41.         aFile = new RandomAccessFile("C:/goods.txt""rw");  
  42.         inChannel = aFile.getChannel();  
  43.         RandomAccessFile bFile = new RandomAccessFile("C:/22.log""rw");  
  44.         FileChannel outChannel = bFile.getChannel();  
  45.         inChannel.transferTo(0, inChannel.size(), outChannel);  
  46.         System.out.println("Copy over");  
  47.     }  
  48.       
  49.     public static void main(String[] args) throws IOException {  
  50.         NioFileCopy tool = new NioFileCopy();  
  51.         //tool.doWrite();  
  52.         //tool.doRead();  
  53.         tool.doCopy();  
  54.     }  
  55. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值