JAVA 是一個廣泛使用的編程語言,它可以用來處理各種文件格式,包括 DOC 和 DOCX。DOC 是 Microsoft Word 的舊文件格式,而 DOCX 是較新的文件格式。
以下是使用 JAVA 實現(xiàn) DOC 和 DOCX 文件格式互相轉(zhuǎn)換的示例代碼:
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import org.apache.poi.xwpf.converter.core.XWPFConverterException; import org.apache.poi.xwpf.converter.pdf.PdfConverter; import org.apache.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.xwpf.usermodel.XWPFDocument; public class FileConverter { public static void convertDocToHtml(String fileName) { try { FileInputStream inStream = new FileInputStream(new File(fileName)); HWPFDocument doc = new HWPFDocument(inStream); WordToHtmlConverter converter = new WordToHtmlConverter( DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ); converter.processDocument(doc); File outFile = new File(fileName + ".html"); FileOutputStream outStream = new FileOutputStream(outFile); converter.processDocument(doc); String html = converter.getDocumentContent().toString(); outStream.write(html.getBytes()); inStream.close(); outStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static void convertDocxToPdf(String fileName) { try { FileInputStream inStream = new FileInputStream(new File(fileName)); XWPFDocument document = new XWPFDocument(inStream); File outFile = new File(fileName + ".pdf"); FileOutputStream outStream = new FileOutputStream(outFile); PdfOptions options = PdfOptions.create(); PdfConverter.getInstance().convert(document, outStream, options); inStream.close(); outStream.close(); } catch (XWPFConverterException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
以上代碼演示了如何將 DOC 文件轉(zhuǎn)換為 HTML 格式,和如何將 DOCX 文件轉(zhuǎn)換為 PDF 格式。希望這個代碼示例能夠幫助你解決文件格式轉(zhuǎn)換的問題。