如何使用NIO的文件流高效复制文件?

更新于
2026-10-12 09:27:19
1阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计106个文字,预计阅读时间需要1分钟。

如何使用NIO的文件流高效复制文件?

javapublic static void nioCopyFile(String resource, String destination) throws IOException { Files.copy(Paths.get(resource), Paths.get(destination));}

如何使用NIO的文件流高效复制文件?

NIO与文件流合作复制文件

public static void nioCopyFile(String resource, String destination) throws IOException { FileInputStream fis = new FileInputStream(resource); FileOutputStream fos = new FileOutputStream(destination); FileChannel readChannel = fis.getChannel(); //读文件通道 FileChannel writeChannel = fos.getChannel(); //写文件通道 ByteBuffer buffer = ByteBuffer.allocate(1024); //读入数据缓存 while (true) { buffer.clear(); int len = readChannel.read(buffer); //读入数据 if (len == -1) { break; //读取完毕 } buffer.flip(); writeChannel.write(buffer); //写入文件 } readChannel.close(); writeChannel.close(); }

本文共计106个文字,预计阅读时间需要1分钟。

如何使用NIO的文件流高效复制文件?

javapublic static void nioCopyFile(String resource, String destination) throws IOException { Files.copy(Paths.get(resource), Paths.get(destination));}

如何使用NIO的文件流高效复制文件?

NIO与文件流合作复制文件

public static void nioCopyFile(String resource, String destination) throws IOException { FileInputStream fis = new FileInputStream(resource); FileOutputStream fos = new FileOutputStream(destination); FileChannel readChannel = fis.getChannel(); //读文件通道 FileChannel writeChannel = fos.getChannel(); //写文件通道 ByteBuffer buffer = ByteBuffer.allocate(1024); //读入数据缓存 while (true) { buffer.clear(); int len = readChannel.read(buffer); //读入数据 if (len == -1) { break; //读取完毕 } buffer.flip(); writeChannel.write(buffer); //写入文件 } readChannel.close(); writeChannel.close(); }