前言
在 java 开发中,我们经常需要读取不同类型的文件,包括 excel 表格文件、"doc" 和 "docx" 文档文件、pdf 文件以及纯文本文件。
其中最常用的是 apache poi 库。apache poi 是一个流行的 java 库,提供了许多 api 来读取和写入 microsoft office 文档,包括 excel、word 和 powerpoint 等。
本文将介绍如何使用 java 读取这些不同类型的文件。(本文的方法可供参考,还有其它方法读者自行查阅。)
1.举个栗子
以下是本人在开发过程中,读取"doc"、"docx"、"pdf" 和 "txt" 文件的代码例子,后面将详细解释。
txt文件读取不多说,用流读取。
import org.apache.pdfbox.pdmodel.pddocument;
import org.apache.pdfbox.text.pdftextstripper;
import org.apache.poi.hwpf.extractor.wordextractor;
import org.apache.poi.xwpf.extractor.xwpfwordextractor;
import org.apache.poi.xwpf.usermodel.xwpfdocument;
//fileextension文件后缀名
private string readfilecontent(multipartfile file, string fileextension) throws ioexception {
byte[] filebytes = file.getbytes();
if (filebytes.length == 0){
throw new businessexception(resultcodeenum.file_content_is_empty);
}
switch (fileextension) {
case "txt":
return new string(filebytes, standardcharsets.utf_8);
case "pdf":
try (pddocument doc = pddocument.load(file.getinputstream())) {
pdftextstripper textstripper = new pdftextstripper();
return textstripper.gettext(doc);
}
case "docx":
try (inputstream stream = file.getinputstream()) {
xwpfdocument xdoc = new xwpfdocument(stream);
xwpfwordextractor extractor = new xwpfwordextractor(xdoc);
return extractor.gettext();
}
case "doc":
try (inputstream stream = file.getinputstream()) {
wordextractor extractor = new wordextractor(stream);
return extractor.gettext();
}
default:
log.error("不支持的文件格式");
return null;
}
}2.导入依赖包
<dependencies>
<!-- apache poi 读取和写入 microsoft office 文档 -->
<dependency>
<groupid>org.apache.poi</groupid>
<artifactid>poi</artifactid>
<version>5.0.0</version>
</dependency>
<dependency>
<groupid>org.apache.poi</groupid>
<artifactid>poi-ooxml</artifactid>
<version>5.0.0</version>
</dependency>
<!-- apache pdfbox 处理 pdf 文件 -->
<dependency>
<groupid>org.apache.pdfbox</groupid>
<artifactid>pdfbox</artifactid>
<version>2.0.24</version>
</dependency>
<!-- apache tika 自动检测和提取元数据和文本内容 -->
<dependency>
<groupid>org.apache.tika</groupid>
<artifactid>tika-core</artifactid>
<version>2.1.0</version>
</dependency>
<!-- itext 处理 pdf 文件 -->
<dependency>
<groupid>com.itextpdf</groupid>
<artifactid>itextpdf</artifactid>
<version>5.5.13</version>
</dependency>
</dependencies>
1.读取pdf
读取 pdf 文件可以使用 apache pdfbox 库。以下是一个示例代码,用于读取 pdf 文件的文本内容:
import org.apache.pdfbox.pdmodel.pddocument;
import org.apache.pdfbox.text.pdftextstripper;
import java.io.file;
import java.io.ioexception;
public class pdfreaderexample {
public static void main(string[] args) {
try {
// 1. 加载 pdf 文档
file file = new file("path_to_your_pdf_file.pdf");
pddocument document = pddocument.load(file);
// 2. 创建 pdftextstripper 对象,并提取文本内容
pdftextstripper textstripper = new pdftextstripper();
string content = textstripper.gettext(document);
// 3. 输出文本内容
system.out.println(content);
// 4. 关闭 pdf 文档
document.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
请确保将 path_to_your_pdf_file.pdf 替换为实际的 pdf 文件路径。通过调用 pddocument.load() 方法加载 pdf 文件,然后创建一个 pdftextstripper 对象,并使用 gettext() 方法提取文本内容。最后,使用 document.close() 方法关闭 pdf 文档。
pddocument.load() 方法接受多种类型的参数来加载 pdf 文档。以下是常用的参数类型:
file 对象: 可以传递一个 java.io.file 对象,指向要加载的 pdf 文件。例如:
pddocument.load(new file("path_to_your_pdf_file.pdf"))。文件路径字符串: 可以直接传递一个字符串,表示要加载的 pdf 文件的路径。例如:
pddocument.load("path_to_your_pdf_file.pdf")。inputstream 对象: 可以传递一个
java.io.inputstream对象,从中读取 pdf 内容。例如:pddocument.load(inputstream)。randomaccessread 对象: 可以传递一个
org.apache.pdfbox.io.randomaccessread对象,用于随机访问和读取 pdf 内容。例如:pddocument.load(randomaccessread)。
使用不同的参数类型,可以根据你的需求来加载 pdf 文档。请注意,无论使用哪种方式,都需要正确处理可能抛出的 ioexception 异常,并在使用完 pddocument 对象后调用 close() 方法关闭文档以释放资源。
2.读取docx
读取 docx 文件,可以使用 apache poi 库。
import org.apache.poi.xwpf.usermodel.xwpfdocument;
import org.apache.poi.xwpf.usermodel.xwpfparagraph;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
public class docxreaderexample {
public static void main(string[] args) {
try {
// 1. 加载 docx 文档
file file = new file("path_to_your_docx_file.docx");
inputstream fis = new fileinputstream(file);
xwpfdocument document = new xwpfdocument(fis);
// 2. 提取文本内容
stringbuilder content = new stringbuilder();
for (xwpfparagraph paragraph : document.getparagraphs()) {
content.append(paragraph.gettext());
content.append("\n");
}
// 3. 输出文本内容
system.out.println(content.tostring());
// 4. 关闭 docx 文档
document.close();
fis.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
通过创建一个 fileinputstream 对象,并将其传递给 xwpfdocument 构造函数,来加载 docx 文件。然后,通过遍历文档中的段落,使用 gettext() 方法提取文本内容,并将其存储在一个 stringbuilder 中。最后,输出文本内容。
提取文本内容,提供另外一种方法。
xwpfdocument document = new xwpfdocument(fis); // 2. 提取文本内容 xwpfwordextractor extractor = new xwpfwordextractor(document); string text = extractor.gettext();
xwpfwordextractor 是 apache poi 库中的一个类,用于从 xwpfdocument 对象中提取文本。
然后,调用 gettext() 方法,通过 extractor 对象提取文本内容。该方法会返回一个包含整个文档纯文本的字符串。
3.读取doc
读取 doc(.doc)文件,可以使用 apache poi 库中的 hwpf 模块
import org.apache.poi.hwpf.hwpfdocument;
import org.apache.poi.hwpf.extractor.wordextractor;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
public class doctextextractor {
public static string extracttextfromdoc(string filepath) {
try {
// 1. 加载 doc 文档
file file = new file(filepath);
fileinputstream fis = new fileinputstream(file);
hwpfdocument document = new hwpfdocument(fis);
// 2. 提取文本内容
wordextractor extractor = new wordextractor(document);
string text = extractor.gettext();
// 3. 关闭 doc 文档和提取器
extractor.close();
document.close();
fis.close();
// 4. 返回提取的文本内容
return text;
} catch (ioexception e) {
e.printstacktrace();
}
return null;
}
public static void main(string[] args) {
string filepath = "path_to_your_doc_file.doc";
string extractedtext = extracttextfromdoc(filepath);
system.out.println(extractedtext);
}
}
4.读取excel
1.使用 apache poi 库读取 excel 文件
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import org.apache.poi.ss.usermodel.cell;
import org.apache.poi.ss.usermodel.row;
import org.apache.poi.ss.usermodel.sheet;
import org.apache.poi.xssf.usermodel.xssfworkbook;
public class excelreader {
public static void main(string[] args) throws ioexception {
file file = new file("path/to/excel/file");
fileinputstream inputstream = new fileinputstream(file);
xssfworkbook workbook = new xssfworkbook(inputstream);
sheet sheet = workbook.getsheetat(0);
for (row row : sheet) {
for (cell cell : row) {
system.out.print(cell.tostring() + "\t");
}
system.out.println();
}
workbook.close();
}
}
首先创建了一个 file 对象来表示要读取的 excel 文件,然后创建了一个 fileinputstream 对象来读取文件。接着,我们使用 xssfworkbook 类创建了一个 workbook 对象来表示整个 excel 文档,并获取了第一个工作表(即索引为 0 的工作表)。
在循环中,我们首先遍历每一行 (row),然后再遍历每一列 (cell)。我们可以使用 cell.tostring() 方法获取单元格的值,并打印出来。最后,我们调用 workbook.close() 方法关闭工作簿,释放资源。
2.使用easyexcel
easyexcel 是一款开源的 java excel 操作工具,它提供了简单易用的 api 来读取、写入和操作 excel 文件。
<dependency>
<groupid>com.alibaba</groupid>
<artifactid>easyexcel</artifactid>
<version>2.4.3</version>
</dependency>
读取excel文件
import com.alibaba.excel.easyexcel;
import com.alibaba.excel.read.builder.excelreaderbuilder;
import com.alibaba.excel.read.listener.readlistener;
public class excelreader {
public static void main(string[] args) {
string filepath = "path_to_your_excel_file.xlsx";
// 创建 excel 读取器
excelreaderbuilder readerbuilder = easyexcel.read(filepath);
// 注册读取监听器
readlistener<object> listener = new yourreadlistener();
readerbuilder.registerreadlistener(listener);
// 执行读取操作
readerbuilder.sheet().doread();
}
}
通过 easyexcel.read(filepath) 创建了一个 excel 读取器,然后通过 registerreadlistener() 方法注册了一个读取监听器,你需要自己实现一个 readlistener 的子类,并在其中重写相应的方法来处理读取到的数据。最后,通过 sheet().doread() 方法执行读取操作。
总结
到此这篇关于java读取excel、docx、pdf和txt等文件万能方法的文章就介绍到这了,更多相关java读取excel、docx、pdf和txt文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论