java实现文件复制
时间: 2023-03-03 19:06:24 浏览: 88
以下是Java实现文件复制的示例代码:
```java
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
String sourceFilePath = "C:/source_file.txt";
String destinationFilePath = "C:/destination_file.txt";
try {
File sourceFile = new File(sourceFilePath);
File destinationFile = new File(destinationFilePath);
InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
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("文件复制完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,源文件路径和目标文件路径都被硬编码为字符串。你可以根据需要修改这些字符串。在try块中,我们创建了源文件和目标文件的File对象。然后,我们使用FileInputStream和FileOutputStream类创建了输入和输出流。我们使用while循环从输入流读取数据,并将读取到的数据写入输出流中。最后,我们关闭了输入和输出流,打印出“文件复制完成”的消息。