用java写个文件复制代码
时间: 2024-03-13 20:42:21 浏览: 17
好的,以下是使用 Java 语言实现文件复制的代码:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
File source = new File("source.txt"); // 源文件
File target = new File("target.txt"); // 目标文件
copyFile(source, target); // 调用复制文件的方法
}
public static void copyFile(File source, File target) {
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码中,我们使用了 Java 中的 File 类来表示源文件和目标文件,使用 try-with-resources 语句来自动关闭输入流和输出流。在复制文件时,我们使用了一个缓冲区 byte 数组,每次读取 1024 个字节,并将其写入输出流中。最后,我们在 try 语句块外输出一条复制成功的信息。