最近在做文件解压遇到个问题,记录下解决过程。
文件来源是通过接口获取文件流,然后通过文件流解压文件。
此时需要将文件流写入文件然后对文件进行操作,
遇到的问题是怎么创建合格File对象,搜索了很长时间不得解,
最后发现可以通过 createTempFile来创建
File file = File.createTempFile(fileName, suffix);
具体代码如下:
```java
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipDemo { private static final Log log = LogFactory.getLog(ZipDemo.class); /** * 通过文件流解压文件 * * @throws IOException e */ public static void method() throws IOException { // inputStream为通过接口或者文件下载获取的文件流,此处为模拟数据 ByteArrayOutputStream baos = null; FileOutputStream fos = null; try (InputStream inputStream = new FileInputStream(File.createTempFile("压缩文件", ".zip")); ZipInputStream zipInputStream = new ZipInputStream(inputStream)) { ZipEntry ze; while ((ze = zipInputStream.getNextEntry()) != null) { if (ze.isDirectory()) { continue; } byte[] buf = new byte[1024]; int length; baos = new ByteArrayOutputStream(); while ((length = zipInputStream.read(buf)) != -1) { baos.write(buf, 0, length); baos.flush(); } byte[] data = baos.toByteArray(); // 文件名 String fileName = "文件名"; // 文件后缀 String suffix = ".jpg"; File file = File.createTempFile(fileName, suffix); file.deleteOnExit(); fos = new FileOutputStream(file); fos.write(data); // 此时,file文件已经有了内容,可以对文件进行读写,上传下载等操作了 fos.close(); baos.close(); } } catch (Exception e) { log.info("执行异常"); } finally { if (fos != null) { fos.close(); } if (baos != null) { baos.close(); } } } }