用两种方法实现文件的拷贝功能。 ①用FileInputStream/FileOutputStream ②用BufferedInputStream/BufferedOutputStream
时间: 2023-12-04 20:40:44 浏览: 33
以下是两种实现文件拷贝功能的方法:
1.使用FileInputStream/FileOutputStream:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("source.txt");
FileOutputStream output = new FileOutputStream("target.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
input.close();
output.close();
System.out.println("文件拷贝成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2.使用BufferedInputStream/BufferedOutputStream:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
try {
BufferedInputStream input = new BufferedInputStream(new FileInputStream("source.txt"));
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("target.txt"));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
input.close();
output.close();
System.out.println("文件拷贝成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)