ByteArrayInputStream 转化为文件保存到本地,写一段实例代码
时间: 2023-11-19 22:02:50 浏览: 42
可以按照以下步骤将 ByteArrayInputStream 转换为文件并保存到本地:
1. 创建一个名为 file 的 File 对象,指定要保存的文件路径和名称。
2. 创建一个 FileOutputStream 对象,将其与 file 对象关联。
3. 创建一个 byte 数组,用于存储从 ByteArrayInputStream 中读取的数据。
4. 循环读取 ByteArrayInputStream 中的数据,并将其写入 FileOutputStream 中。
5. 关闭 FileOutputStream 和 ByteArrayInputStream。
下面是一个示例代码:
```java
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteArrayInputStreamToFileExample {
public static void main(String[] args) {
// 示例数据
byte[] data = "Hello, world!".getBytes();
// 创建 ByteArrayInputStream
ByteArrayInputStream bais = new ByteArrayInputStream(data);
// 创建要保存的文件对象
File file = new File("example.txt");
try {
// 创建 FileOutputStream
FileOutputStream fos = new FileOutputStream(file);
// 读取 ByteArrayInputStream 中的数据并写入 FileOutputStream
byte[] buffer = new byte[1024];
int len;
while ((len = bais.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
// 关闭流
fos.close();
bais.close();
System.out.println("File saved successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码将会创建一个名为 example.txt 的文件,并将 ByteArrayInputStream 中的数据写入该文件中。