您的位置:首页 > 其它

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

2017-08-11 17:46 357 查看
内容:通过NIO中的FileChannel完成文件的读、写、复制。

[java] view
plain copy

public class NioFileCopy {  

    private RandomAccessFile aFile = null;  

    private FileChannel inChannel = null;  

    private final ByteBuffer buf = ByteBuffer.allocate(1024);  

      

    public void doWrite() throws IOException {  

        aFile = new RandomAccessFile("C:/goods.txt", "rw");  

        inChannel = aFile.getChannel();  

        String newData = "New String to wirte to file... " + System.currentTimeMillis();  

        buf.clear();  

        buf.put(newData.getBytes());  

          

        buf.flip();  

          

        while (buf.hasRemaining())   

            inChannel.write(buf);  

          

        inChannel.close();  

        System.out.println("Write Over");  

    }  

      

    public void doRead() throws IOException {  

        aFile = new RandomAccessFile("C:/goods.txt", "rw");  

        inChannel = aFile.getChannel();  

          

        int bytesRead = inChannel.read(buf);  

        while (bytesRead != -1) {  

            System.out.println("Read " + bytesRead);  

            buf.flip();  

            while (buf.hasRemaining())  

                System.out.print((char) buf.get());  

              

            buf.clear();  

            bytesRead = inChannel.read(buf);  

        }  

          

        aFile.close();  

    }  

      

    public void doCopy() throws IOException {  

        aFile = new RandomAccessFile("C:/goods.txt", "rw");  

        inChannel = aFile.getChannel();  

        RandomAccessFile bFile = new RandomAccessFile("C:/22.log", "rw");  

        FileChannel outChannel = bFile.getChannel();  

        inChannel.transferTo(0, inChannel.size(), outChannel);  

        System.out.println("Copy over");  

    }  

      

    public static void main(String[] args) throws IOException {  

        NioFileCopy tool = new NioFileCopy();  

        //tool.doWrite();  

        //tool.doRead();  

        tool.doCopy();  

    }  

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