将d盘下的xxx.jar(200M左右)文件复制到e盘下 1、 利用输入输出流完成文件的复制 2、 利用缓冲输入输出流完成文件的复制 3、 对比速度
时间: 2024-03-17 20:41:29 浏览: 10
好的,这是一个关于文件复制的问题,我可以帮你解答。这里提供三种实现方式:
1. 利用输入输出流完成文件复制
```java
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
String sourcePath = "D:/xxx.jar";
String targetPath = "E:/xxx.jar";
try (InputStream in = new FileInputStream(sourcePath);
OutputStream out = new FileOutputStream(targetPath)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 利用缓冲输入输出流完成文件复制
```java
import java.io.*;
public class CopyFileBuffered {
public static void main(String[] args) {
String sourcePath = "D:/xxx.jar";
String targetPath = "E:/xxx.jar";
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourcePath));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(targetPath))) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 对比速度
我们可以使用Java自带的System.currentTimeMillis()方法来计算复制时间,然后比较两种方式的时间差异。
```java
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
String sourcePath = "D:/xxx.jar";
String targetPath = "E:/xxx.jar";
try (InputStream in = new FileInputStream(sourcePath);
OutputStream out = new FileOutputStream(targetPath)) {
byte[] buffer = new byte[1024];
int len;
long start = System.currentTimeMillis();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
long end = System.currentTimeMillis();
System.out.println("普通IO复制时间:" + (end - start) + "ms");
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourcePath));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(targetPath))) {
byte[] buffer = new byte[1024];
int len;
long start = System.currentTimeMillis();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
long end = System.currentTimeMillis();
System.out.println("缓冲IO复制时间:" + (end - start) + "ms");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
通过测试可以发现,使用缓冲输入输出流复制文件的速度比使用普通输入输出流快。