这几天在学习java io流的东西,有一个网友看到博客后问了一个问题,就是说他的doc文档为什么用我所说的方法死活就是乱码。
我一开始以为是他方法问题,结果自己试了之后发现和他的结果一样也是乱码。
于是在网上搜寻了一阵之后才发现原来doc文档和excel一样不能用普通的io流的方法来读取,而是也需要用poi,于是进行了一番尝试后,终于以正确的编码格式读取了这个doc文件。
在网上搜索的过程中发现doc和docx的读取方法是不一样的,于是顺带也学了一下docx文件的简单读取。
一、导包:
doc文件的读取,需要导入poi-scratchpad的jar包和相关依赖包:
docx文件读取,需要导入poi-ooxml的jar包和相关依赖包:
我用的是maven构建项目,相关的依赖包会自动导入,maven导包配置如下:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.8</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
二、读取文件的代码:
1、doc文件读取简单示例:
public static void readAndWriterTest3() throws IOException {
File file = new File("C:\\Users\\tuzongxun123\\Desktop\\aa.doc");
String str = "";
try {
FileInputStream fis = new FileInputStream(file);
HWPFDocument doc = new HWPFDocument(fis);
String doc1 = doc.getDocumentText();
System.out.println(doc1);
StringBuilder doc2 = doc.getText();
System.out.println(doc2);
Range rang = doc.getRange();
String doc3 = rang.text();
System.out.println(doc3);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
2、docx文件读取简单示例:
public static void readAndWriterTest4() throws IOException {
File file = new File("C:\\Users\\tuzongxun123\\Desktop\\aa.docx");
String str = "";
try {
FileInputStream fis = new FileInputStream(file);
XWPFDocument xdoc = new XWPFDocument(fis);
XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
String doc1 = extractor.getText();
System.out.println(doc1);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
//20171218修改
我并没有在工作中操作过word,这篇博客也只是一时兴起所做,因此写的很简单。
而最近陆续有朋友找我询问相关的问题,其中有好几个都在询问依赖包有哪些,为了避免一再回答这种问题,特将依赖包截图: