java实现doc文件流转docx文件流
1. 引入依赖
<!-- https://mvnrepository.com/artifact/com.aspose/aspose-words -->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>18.2.0</version>
</dependency>
jar下载链接:https://pan.baidu.com/s/1203Xn9JgJ1tG6cWPkythAA?pwd=rea4
提取码:rea4
2. InputStream转字节数组,并关闭流
byte[] docBytes = FileCopyUtils.copyToByteArray(docInputStream);
3. 使用ByteArrayOutputStream接收docx文件流
try (
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream sbs = new ByteArrayInputStream(arrays)
) {
com.aspose.words.Document doc = new com.aspose.words.Document(sbs);
doc.save(os, SaveFormat.DOCX);
4.字节数组转InputStream
new ByteArrayInputStream(docxBytes)
5. 完整代码
/**
* doc转为docx
* @param docInputStream
* @return
* @throws IOException
*/
public static InputStream convertDocIs2DocxIs(InputStream docInputStream) throws IOException {
byte[] docBytes = FileCopyUtils.copyToByteArray(docInputStream);
byte[] docxBytes = convertDocStream2docxStream(docBytes);
return new ByteArrayInputStream(docxBytes);
}
// 将doc字节数组转换为docx字节数组
public static byte[] convertDocStream2docxStream(byte[] arrays) {
byte[] docxBytes = new byte[1];
if (arrays != null && arrays.length > 0) {
try (
ByteArrayOutputStream os = new ByteArrayOutputStream();
InputStream sbs = new ByteArrayInputStream(arrays)
) {
com.aspose.words.Document doc = new com.aspose.words.Document(sbs);
doc.save(os, SaveFormat.DOCX);
docxBytes = os.toByteArray();
} catch (Exception e) {
System.out.println("出错啦");
}
}
return docxBytes;
}