毫無疑問支持.doc和.docx的只有POI
好多jar都是積分下載,要麼就是官網下載,真心垃圾,jar包免費下載:
鏈接:https://pan.baidu.com/s/14MWWHN3cTsr0mmxMGkIObQ
提取碼:93ob
複製這段內容後打開百度網盤手機App,操作更方便哦
新增支持讀取txt文本和pdf,pdf需要iTextpdf.jar包,從上方鏈接下載即可
/**
* 讀取txt文件
*
* @param filepath 本地txt或log文件
* @return 返回讀取到的文件內容
*/
public static String readFileContent(String filepath) {
String content = "";
try {
InputStream is = new FileInputStream(new File(filepath));
InputStreamReader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
content = content + line + "\n";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.toString();
}
return content;
}
/**
* 讀取word內容
*
* @param path
*/
public static String readDoc(String path) {
String content = "";
try {
FileInputStream in = new FileInputStream(path);
//PoiFs 主要類 管理整個文件系統生命週期
POIFSFileSystem pfs = new POIFSFileSystem(in);
//獲取文檔所有的數據結構 可以說是一個“文檔對象”
HWPFDocument hwpf = new HWPFDocument(pfs);
content = hwpf.getText().toString();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
/**
* 讀取word內容
*
* @param path
*/
public static String readDocx(String path) {
String content = "";
try {
InputStream is = new FileInputStream(path);
XWPFDocument doc = new XWPFDocument(is);
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
content = extractor.getText();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
/**
* 讀取Pdf文件的內容
*
* @param path :文件地址
*/
public String readPdf(String path) {
String content = "";
try {
PdfReader pr = new PdfReader(path);
int page = pr.getNumberOfPages();
for (int i = 1; i < page + 1; i++) {
content += PdfTextExtractor.getTextFromPage(pr, i);
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}