文件通道FileChannel使用

介绍

文件通道FileChannel是用于读取,写入,文件的通道。FileChannel只能被InputStream、OutputStream、RandomAccessFile创建。FileChannel通过字节流创建,那么操作的缓冲区肯定就是字节缓冲区。

读写例子

public class FileChannelTest {
    
    // 使用通道读文件
    public void readData(File file) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            FileChannel fc = fis.getChannel();
            // 创建缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);
            // 从通道读取数据到缓冲区
            fc.read(buf);
            // 反转缓冲区(limit设置为position,position设置为0,mark设置为-1)
            buf.flip();
            // 就是判断position和limit之间是否有元素
            while (buf.hasRemaining()) {
                // 按照字节的格式获取数据
                System.out.print((char) buf.get());
            }
            // 读完将缓冲区还原(position设置为0,limit设置为capacity,mark设置为-1)
            buf.clear();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    // 使用通道写文件
    public void writeData(File file , String data) {
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream(file);
            FileChannel fc = fos.getChannel();
            // 创建缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);
            // 将数据装入缓冲区
            buf.put(data.getBytes());
            // 反转缓冲区(limit设置为position,position设置为0,mark设置为-1)
            buf.flip();
            // 将缓冲区中的数据写入到通道
            fc.write(buf);
            // 写完将缓冲区还原(position设置为0,limit设置为capacity,mark设置为-1)
            buf.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        final FileChannelTest test = new FileChannelTest();
        File file = new File("E:\\StringTest.java");
        test.readData(file);
        test.writeData(file, "123456789");
    }
}

结果:


1.jpg

FileChannel的源码:
https://www.jianshu.com/p/ecfacec90357

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容