在Java中读取文档内容是一项常见的操作,根据文档类型的不同(如文本文件、PDF、Word、Excel等),实现方法也有所差异,本文将详细介绍几种常见文档类型的读取方式,涵盖基础文本文件到复杂办公文档的处理,并提供核心代码示例和注意事项,帮助开发者高效实现文档内容解析。

读取文本文件(.txt)
文本文件是最基础的文档类型,Java提供了多种读取方式,包括字节流和字符流,对于普通文本文件,推荐使用字符流(Reader及其子类),因为它能更好地处理字符编码问题。
使用BufferedReader逐行读取
BufferedReader是Reader的装饰类,通过缓冲机制提高读取效率,特别适合逐行读取文本文件,核心代码如下:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TextFileReader {
public static void main(String[] args) {
String filePath = "example.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项:
- 使用try-with-resources语句确保资源自动关闭,避免内存泄漏。
- FileReader默认使用系统字符编码,若文件编码为UTF-8等,需指定编码:
new InputStreamReader(new FileInputStream(filePath), "UTF-8")。
使用Files类(Java 7+)
Java 7引入的java.nio.file.Files类提供了更简洁的API,支持按行读取或一次性读取全部内容:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class FilesReaderExample {
public static void main(String[] args) {
String filePath = "example.txt";
try {
// 一次性读取全部内容
String content = new String(Files.readAllBytes(Paths.get(filePath)));
System.out.println(content);
// 按行读取
Files.lines(Paths.get(filePath)).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取Word文档(.docx)
对于Word文档,通常使用Apache POI库或docx4j库,这里以Apache POI为例,说明.docx文件的读取方法。

添加依赖
Maven项目中需添加以下依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
核心代码示例
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
public class WordReader {
public static void main(String[] args) {
String filePath = "example.docx";
try (FileInputStream fis = new FileInputStream(filePath);
XWPFDocument document = new XWPFDocument(fis)) {
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph para : paragraphs) {
System.out.println(para.getText());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项:
- Apache POI对.doc(旧版Word)的支持需要额外依赖(
poi-scratchpad),且处理较复杂。 - 大文件读取时,注意内存管理,可结合
XWPFWordExtractor提取纯文本。
读取PDF文档
PDF文档的读取通常需要第三方库,如Apache PDFBox或iText,这里以PDFBox为例。
添加依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
核心代码示例
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.IOException;
public class PdfReader {
public static void main(String[] args) {
String filePath = "example.pdf";
try (PDDocument document = PDDocument.load(new File(filePath))) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项:
- PDFBox提取的文本可能因PDF格式(如扫描件、图片型PDF)而丢失内容,需结合OCR技术处理。
- 大文件读取时,避免一次性加载所有页面,可分页处理。
读取Excel文档(.xlsx)
Excel文档的读取同样依赖Apache POI,针对.xlsx(OOXML格式)使用XSSFAPI。

核心代码示例
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) {
String filePath = "example.xlsx";
try (FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook(fis)) {
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
String cellValue = sheet.getRow(i).getCell(0).getStringCellValue();
System.out.println(cellValue);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项:
- 单元格类型需匹配读取方法(如
getNumericCellValue()处理数字)。 - 处理合并单元格时,需额外判断
MergedRegion。
总结与最佳实践
- 选择合适的工具:根据文档类型选择库,如文本文件用Java IO/NIO,Word/Excel用POI,PDF用PDFBox。
- 编码规范:始终指定文件编码(如UTF-8),避免乱码。
- 异常处理:捕获并处理
IOException,确保程序健壮性。 - 资源管理:优先使用try-with-resources,避免资源泄漏。
- 性能优化:大文件采用流式读取或分批处理,避免内存溢出。
通过以上方法,开发者可以灵活应对各类文档内容的读取需求,结合具体场景选择最优方案,实现高效、稳定的文档解析功能。


















