java实现doc转docx的几种方式
时间: 2023-06-20 13:07:25 浏览: 7003
Java将doc转docx工具类方法,maven项目,Idea可直接运行
5星 · 资源好评率100%
1. 使用Apache POI库进行转换:
```java
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToConverter;
import org.apache.poi.hwpf.usermodel.Range;
import java.io.*;
public class DocToDocxConverter {
public static void main(String[] args) throws Exception {
// 读取doc文件
InputStream inputStream = new FileInputStream("test.doc");
HWPFDocument document = new HWPFDocument(inputStream);
// 转换为docx文件
WordToConverter converter = new WordToConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
converter.processDocument(document);
// 写入docx文件
OutputStream outputStream = new FileOutputStream("test.docx");
converter.getDocument().write(outputStream);
// 关闭流
outputStream.close();
inputStream.close();
}
}
```
2. 使用Aspose.Words库进行转换:
```java
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import java.io.*;
public class DocToDocxConverter {
public static void main(String[] args) throws Exception {
// 读取doc文件
InputStream inputStream = new FileInputStream("test.doc");
Document document = new Document(inputStream);
// 转换为docx文件
document.save("test.docx", SaveFormat.DOCX);
// 关闭流
inputStream.close();
}
}
```
3. 使用JodConverter库进行转换:
```java
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;
public class DocToDocxConverter {
public static void main(String[] args) throws Exception {
// 创建IConverter对象
IConverter converter = LocalConverter.builder().build();
// 读取doc文件
InputStream inputStream = new FileInputStream("test.doc");
// 写入docx文件
OutputStream outputStream = new FileOutputStream("test.docx");
// 转换为docx文件
converter.convert(inputStream).as(DocumentType.MS_WORD).to(outputStream).as(DocumentType.DOCX).execute();
// 关闭流
outputStream.close();
inputStream.close();
// 关闭IConverter对象
converter.shutDown();
}
}
```
阅读全文