java 江inputstream转成File对象
时间: 2023-06-22 19:37:32 浏览: 115
可以通过以下步骤将 InputStream 转换为 File 对象:
1. 创建一个临时文件,可以使用 File 类的 createTempFile() 方法。
2. 使用 FileOutputStream 将 InputStream 写入临时文件。
3. 将临时文件转换为 File 对象,可以使用 File 类的 getAbsoluteFile() 或 getCanonicalFile() 方法。
下面是代码示例:
```
import java.io.*;
public class InputStreamToFileExample {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("input.txt");
// 创建临时文件
File tempFile = File.createTempFile("temp", ".txt");
// 写入临时文件
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
// 将临时文件转换为 File 对象
File file = tempFile.getAbsoluteFile();
System.out.println(file.getAbsolutePath());
}
}
```
注意:在使用完临时文件后,需要将其删除。可以使用 File 类的 delete() 方法。