利用FileChannel实现文件文件复制和读写

FileChannel所实现的是管间通信,与普通的读写不同在进行大文件的读写上有很大的优势;
首先是管道的建立,可以通过I/O流来建立FileChannel;下面是利用通道进行文件复制

public static boolean copy(File start,File end)  {
        try(
                FileInputStream in = new FileInputStream(start);
                FileOutputStream out = new FileOutputStream(end);
                FileChannel fIn  = in.getChannel();
                FileChannel fOut  = out.getChannel();
                ){
            fIn.transferTo(0, fIn.size(),fOut);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

如果要利用FileChannel进行读写,就需要用ByteBuffer类建立一个缓存区,可以通过Charset来指定字节码,然后对缓存区进行解码

public static String read(FileChannel fileChannel, Charset charset) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        StringBuilder stringBuilder = new StringBuilder();
        fileChannel.read(charset.encode("UTE-8"));
        while ( fileChannel.read(buffer) != -1) {
            buffer.flip();
            stringBuilder.append(charset.decode(buffer));
            buffer.clear();
        }

        return stringBuilder.toString();
    }

其中运用了ByteBuffer的flip()方法,这个方法在API上的翻译为:反转此缓冲区。首先对当前位置设置限制,然后将该位置设置为零;相当于说调用这 个方法重头遍历这个缓冲区,并且它的最后长度不会是整个缓冲区长度,而是它读出之前数据的长度;


版权声明:本文为zjgyjd原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。