用java写一个文件复制程序
时间: 2023-12-02 21:03:50 浏览: 30
好的,以下是用 Java 写一个文件复制程序的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
String sourceFile = "path/to/source/file";
String destFile = "path/to/destination/file";
try {
File fileToCopy = new File(sourceFile);
FileInputStream inputStream = new FileInputStream(fileToCopy);
File fileToCreate = new File(destFile);
FileOutputStream outputStream = new FileOutputStream(fileToCreate);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你可以将 `path/to/source/file` 和 `path/to/destination/file` 替换为你要复制的文件的路径和复制后生成的文件的路径。这个程序使用 Java 的 `FileInputStream` 和 `FileOutputStream` 类来读取和写入文件,通过一个循环来每次读取和写入 `1024` 个字节的数据,直到文件被完全复制。