java获取本地io速度
时间: 2023-08-10 14:03:40 浏览: 100
要获取本地IO速度,可以使用Java的NIO(New IO)库中的ByteBuffer和FileChannel类来实现。下面是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class IOBenchmark {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
int bufferSize = 1024 * 1024; // 1MB buffer size
long startTime = System.currentTimeMillis();
copyFile(inputFile, outputFile, bufferSize);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
double fileSize = inputFile.length() / 1024.0 / 1024.0;
double ioSpeed = fileSize / (duration / 1000.0);
System.out.printf("IO speed: %.2f MB/s\n", ioSpeed);
}
public static void copyFile(File inputFile, File outputFile, int bufferSize) throws IOException {
try (FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
FileChannel inputChannel = inputStream.getChannel();
FileChannel outputChannel = outputStream.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
while (inputChannel.read(buffer) != -1) {
buffer.flip();
outputChannel.write(buffer);
buffer.clear();
}
}
}
}
```
这个程序会从本地文件系统中读取一个文件,并将其拷贝到另一个文件中,然后计算拷贝速度。你可以根据自己的需求修改bufferSize值来测试不同大小的缓冲区大小对IO速度的影响。
阅读全文