用FileInputStream,FileOutputStream实现将一个目录下的某一二进制文件复制到另一个目录
时间: 2023-07-14 18:12:41 浏览: 42
可以按照以下步骤实现:
1. 创建源文件和目标文件的 File 对象。
```java
File sourceFile = new File("sourceDir/sourceFile.bin");
File targetFile = new File("targetDir/targetFile.bin");
```
2. 创建 FileInputStream 和 FileOutputStream 对象。
```java
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
```
3. 创建 byte 数组用于存储读取的数据。
```java
byte[] buffer = new byte[1024];
```
4. 通过循环读取并写入数据。
```java
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
```
5. 关闭 FileInputStream 和 FileOutputStream 对象。
```java
fis.close();
fos.close();
```
完整代码如下:
```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) throws IOException {
File sourceFile = new File("sourceDir/sourceFile.bin");
File targetFile = new File("targetDir/targetFile.bin");
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)