Java之FileChannel类的理解和使用 -----java 流NIO的使用

1. FileChannel 使用场景:

一个读,写,映射,操作文件的通道。
2 使用的优点
1.在文件的绝对位置的字节读写操作在某种程度上不会影响通道的当前位置。

2.文件的区域可能会被直接映射到内存中,对于大文件来说,这比通常的读写方法更有效。

3.为了保证数据在系统崩溃之后不丢失数据,文件的修改模式会被强制到底层存储设备。

4.字节能从一个文件被转换为一些其他的通道,反之亦然,这种操作在某种程度上会被许多操作系统或者文件系统优化成一个非常快速的直接传输。

5.文件的区域也许会被锁住来防止其它程序的访问。

文件复制小DEMO

 /**
     * 用filechannel进行文件复制
     *
     * @param fromFile 源文件
     * @param toFile   目标文件
     */
    public void fileCopyWithFileChannel(File fromFile, File toFile) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        FileChannel fileChannelInput = null;
        FileChannel fileChannelOutput = null;
        try {
            fileInputStream = new FileInputStream(fromFile);
            fileOutputStream = new FileOutputStream(toFile);
            //得到fileInputStream的文件通道
            fileChannelInput = fileInputStream.getChannel();
            //得到fileOutputStream的文件通道
            fileChannelOutput = fileOutputStream.getChannel();
            //将fileChannelInput通道的数据,写入到fileChannelOutput通道
            fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
                if (fileChannelInput != null)
                    fileChannelInput.close();
                if (fileOutputStream != null)
                    fileOutputStream.close();
                if (fileChannelOutput != null)
                    fileChannelOutput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

项目中的 使用场景

 @Override
    public String upload(String type, InputStream inputStream) {
        FileOutputStream out = null;
        FileChannel channel = null;
        ByteBuffer buffer = null;
        try {
            String name = IdGenerateUtil.generateId(type);
            String fileName = dir + name;
            out = new FileOutputStream(fileName);
            channel = out.getChannel();
            buffer = ByteBuffer.wrap(readStream(inputStream));
            out.flush();
            channel.write(buffer);
            return name;
        } catch (Exception e) {
            LOGGER.error(LogBuilderUtil.getBuilder("upload", "上传文件", "Exception").build(), e);
        } finally {
            try {
                channel.close();
                out.close();
            } catch (IOException e) {
                LOGGER.error(LogBuilderUtil.getBuilder("upload", "上传文件", "finally-Exception").build(), e);
            }
        }
        return null;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java中的FileChannel和ByteBuffer来实现NIO操作,可以提高文件读取效率。以下是一个使用NIO读取文件的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class NIOFileReader { public static void main(String[] args) throws IOException { // 打开文件通道 FileChannel fileChannel = new FileInputStream(new File("file.txt")).getChannel(); // 创建一个缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); // 从文件通道读取数据到缓冲区 while (fileChannel.read(buffer) != -1) { // 切换读写模式 buffer.flip(); // 读取缓冲区中的数据 while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } // 清空缓冲区 buffer.clear(); } // 关闭文件通道 fileChannel.close(); } } ``` 在这个示例中,我们首先打开文件通道,然后创建一个ByteBuffer缓冲区来存储读取到的数据。在循环中,我们使用FileChannel的read()方法将数据读取到缓冲区中,然后使用ByteBuffer的flip()方法切换读写模式,从而可以读取缓冲区中的数据。最后使用ByteBuffer的clear()方法清空缓冲区。 需要注意的是,在使用FileChannel读取数据时,需要先将数据读取到缓冲区中,然后再从缓冲区中读取数据。同时,由于缓冲区的大小是有限的,因此需要在循环中反复读取数据,直到读取到文件的末尾为止。 除了读取数据外,FileChannel还可以用于写入数据、截取文件、移动文件指针等操作。使用Java中的NIO操作可以提高文件读取效率,适用于需要频繁读写文件的场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值