数组,transferFrom,ByteBuffer数据传输对比

本文对比了使用通道、数组和字节缓冲区三种方法进行大文件传输的性能,结果显示通道传输在不同文件大小下表现最佳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cache;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;


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


File inFile = new File("f:\\test\\CopyOfBlockCache.java");
File outFile = new File("f:\\test\\channel\\"
+ (new Random().nextInt()));


/*
 * for (int i = 0; i < 1000; i++) { getOutStream(file); }
 */


InputStream blockIn = getBlockInputStream(inFile);
FileChannel fileCh = ((FileInputStream) blockIn).getChannel();
if (!outFile.getParentFile().exists())
outFile.getParentFile().mkdirs();
OutputStream out = getOutStream(outFile);
long dataLength = 0;
long size = inFile.length();
long everLong = 4 * 1024 * 1024;
long tmp;
long start = System.currentTimeMillis();
while (dataLength < size) {
tmp = ((FileOutputStream) out).getChannel().transferFrom(fileCh,
dataLength, everLong);
dataLength += tmp;
// System.out.println("dataLength="+dataLength);
// System.out.println("everLong="+everLong);
// System.out.println("fileSize="+size+",dataLength="+dataLength);
}
long end = System.currentTimeMillis();
// System.out.println("fileSize="+size+",dataLength="+dataLength+",outFile1="+outFile1.length());
System.out.println("channel tranfer:" + (end - start));


long start1 = System.currentTimeMillis();
File outFile1 = new File("f:\\test\\array\\" + (new Random().nextInt()));
if (!outFile1.getParentFile().exists())
outFile1.getParentFile().mkdirs();
read(inFile, outFile1);
long end1 = System.currentTimeMillis();
System.out.println("array tranfer:" + (end1 - start1));


long start2 = System.currentTimeMillis();
File outFile2 = new File("f:\\test\\bytebuffer\\"
+ (new Random().nextInt()));
if (!outFile2.getParentFile().exists())
outFile2.getParentFile().mkdirs();
readByteBuffer(inFile, outFile2);
long end2 = System.currentTimeMillis();
System.out.println("readByteBuffer tranfer:" + (end2 - start2));


}


public static InputStream getBlockInputStream(File srcFile)
throws IOException {
RandomAccessFile blockInFile;
try {
blockInFile = new RandomAccessFile(srcFile, "r");
} catch (FileNotFoundException fnfe) {
throw new IOException("Expected block file at " + srcFile
+ " does not exist.");
}


return new FileInputStream(blockInFile.getFD());
}


public static OutputStream getOutStream(File targetFile) {
FileOutputStream blockOut = null;


try {
blockOut = new FileOutputStream(new RandomAccessFile(targetFile,
"rw").getFD());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return blockOut;


}


public static void read(File srcFile, File desFile) throws IOException {
OutputStream out = getOutStream(desFile);
InputStream in = getBlockInputStream(srcFile);
byte buf[] = new byte[4 * 1024 * 1024];
int dataLen = 0;
int totalSize = 0;
dataLen = in.read(buf, 0, buf.length);
while (dataLen != -1) {
totalSize += dataLen;


out.write(buf, 0, dataLen);
dataLen = in.read(buf, 0, buf.length);
}
}


public static void readByteBuffer(File srcFile, File desFile)
throws IOException {
FileChannel out = ((FileOutputStream) getOutStream(desFile))
.getChannel();
FileChannel in = ((FileInputStream) getBlockInputStream(srcFile))
.getChannel();


ByteBuffer buf = ByteBuffer.allocate(4 * 1024 * 1024);
while (in.read(buf) != -1) {
buf.flip(); // 准备写
out.write(buf);
buf.clear(); // 准备读
}
}
}


读取4KB小文件:

channel transfer:1
array transfer:9
readByteBuffer transfer:8

读取206MB的大文件:

channel transfer:7118
array transfer:6298
readByteBuffer transfer:12148


### 创建 ByteBuffer 的方法 在 Java 中,`ByteBuffer` 是 NIO 包中的一个重要类,用于处理字节缓冲区。可以通过多种方式创建 `ByteBuffer` 实例,其中一种常见的方式是通过指定容量来创建。 以下是基于数组容量创建 `ByteBuffer` 的两种主要方法: #### 方法一:使用 `allocate(int capacity)` 静态工厂方法 此方法会分配一个新的堆内存区域作为缓冲区的内容存储位置[^1]。 ```java int capacity = 1024; // 定义缓冲区的容量 ByteBuffer buffer = ByteBuffer.allocate(capacity); ``` 上述代码片段展示了如何通过静态方法 `allocate()` 来创建一个具有固定容量的 `ByteBuffer` 对象。该对象会在 JVM 堆上分配空间,并初始化其内部状态,包括 `position`, `limit`, `capacity` 属性[^2]。 #### 方法二:使用 `allocateDirect(int capacity)` 静态工厂方法 如果需要更高效的 I/O 性能,则可以考虑使用直接缓冲区 (direct buffer),它是在本机内存中分配的空间而非 JVM 堆内[^3]。 ```java int directCapacity = cameraHeight * cameraWidth * 4; ByteBuffer frameBuffer = ByteBuffer.allocateDirect(directCapacity); ``` 这里需要注意的是,虽然两者都可以用来保存数据,但是直接缓冲区通常更适合频繁涉及文件或网络通道操作的应用场景,因为它可以直接映射到操作系统级别的资源而无需复制过程。 另外值得注意的一点在于,当调用 `array()` 方法获取底层支持数组时,在非直接缓存情况下返回有效结果;然而对于 DirectByteBuffers 而言,由于它们并不一定由常规Java 数组支撑起结构,因此尝试访问此类信息可能会抛出 UnsupportedOperationException 异常。 ### 关于 Buffer 类的核心属性说明 无论采用哪种方式进行实例化,每一个新构建出来的 ByteBuffer 都具备如下几个基础特性: - **mark**: 记录标记的位置,默认初始值设为 -1 表明尚未设置任何书签; - **position**: 当前读写指针所在处,默认从零开始计数; - **limit**: 可达范围界限,即允许的最大索引加一; - **capacity**: 缓冲区内总可用单元数量,等于实际申请大小且不可更改。 这些字段共同决定了当前缓冲器的工作区间以及行为模式。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值