java读取doc,pdf问题。 50
目标:java读取doc,pdf文件要求:不仅可以读取文件中的文本,也可以读取文件中的图片。需要用到的jar包,和相关方法。或者说明文档。已经用到的jar包:tm-ext...
目标:java读取doc,pdf文件
要求:不仅可以读取文件中的文本,也可以读取文件中的图片。
需要用到的jar包,和相关方法。或者说明文档。
已经用到的jar包:tm-extractors-0.4.jar,PDFBox-0.7.2.jar,PDFBox-0.7.2-log4j.jar,fontbox-1.8.2.jar,pdfbox-1.8.2.jar 展开
要求:不仅可以读取文件中的文本,也可以读取文件中的图片。
需要用到的jar包,和相关方法。或者说明文档。
已经用到的jar包:tm-extractors-0.4.jar,PDFBox-0.7.2.jar,PDFBox-0.7.2-log4j.jar,fontbox-1.8.2.jar,pdfbox-1.8.2.jar 展开
2个回答
展开全部
PDFBox是一个开源的对pdf文件进行操作的库。 PDFBox-0.7.3.jar加入classpath。同时FontBox1.0.jar加入classpath,否则报错
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
public class PdfReader {
/**
* simply reader all the text from a pdf file.
* You have to deal with the format of the output text by yourself.
* 2008-2-25
* @param pdfFilePath file path
* @return all text in the pdf file
*/
public static String getTextFromPDF(String pdfFilePath)
{
String result = null;
FileInputStream is = null;
PDDocument document = null;
try {
is = new FileInputStream(pdfFilePath);
PDFParser parser = new PDFParser(is);
parser.parse();
document = parser.getPDDocument();
PDFTextStripper stripper = new PDFTextStripper();
result = stripper.getText(document);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (document != null) {
try {
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
public static void main(String[] args)
{
String str=PdfReader.getTextFromPDF("C:\\Read.pdf");
System.out.println(str);
}
}
代码2:
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
public class PDFReader {
public void readFdf(String file) throws Exception {
boolean sort = false;
String pdfFile = file;
String textFile = null;
String encoding = "UTF-8";
int startPage = 1;
int endPage = Integer.MAX_VALUE;
Writer output = null;
PDDocument document = null;
try {
try {
// 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件
URL url = new URL(pdfFile);
//注意参数已不是以前版本中的URL.而是File。
document = PDDocument.load(pdfFile);
// 获取PDF的文件名
String fileName = url.getFile();
// 以原来PDF的名称来命名新产生的txt文件
if (fileName.length() > 4) {
File outputFile = new File(fileName.substring(0, fileName
.length() - 4)
+ ".txt");
textFile = outputFile.getName();
}
} catch (MalformedURLException e) {
// 如果作为URL装载得到异常则从文件系统装载
//注意参数已不是以前版本中的URL.而是File。
document = PDDocument.load(pdfFile);
if (pdfFile.length() > 4) {
textFile = pdfFile.substring(0, pdfFile.length() - 4)
+ ".txt";
}
}
output = new OutputStreamWriter(new FileOutputStream(textFile),
encoding);
PDFTextStripper stripper = null;
stripper = new PDFTextStripper();
// 设置是否排序
stripper.setSortByPosition(sort);
// 设置起始页
stripper.setStartPage(startPage);
// 设置结束页
stripper.setEndPage(endPage);
// 调用PDFTextStripper的writeText提取并输出文本
stripper.writeText(document, output);
} finally {
if (output != null) {
// 关闭输出流
output.close();
}
if (document != null) {
// 关闭PDF Document
document.close();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PDFReader pdfReader = new PDFReader();
try {
// 取得E盘下的SpringGuide.pdf的内容
pdfReader.readFdf("C:\\Read.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、抽取支持中文的pdf文件-xpdf
xpdf是一个开源项目,我们可以调用他的本地方法来实现抽取中文pdf文件。
http://www.java-cn.com/technology/tech_downs/1880_004.zip
补丁包:
http://www.java-cn.com/technology/tech_downs/1880_005.zip
按照readme放好中文的patch,就可以开始写调用本地方法的java程序了。
下面是一个如何调用的例子:
import java.io.*;
/**
* <p>Title: pdf extraction</p>
* <p>Description: email:chris@matrix.org.cn</p>
* <p>Copyright: Matrix Copyright (c) 2003</p>
* <p>Company: Matrix.org.cn</p>
* @author chris
* @version 1.0,who use this example pls remain the declare
*/
public class PdfWin {
public PdfWin() {
}
public static void main(String args[]) throws Exception
{
String PATH_TO_XPDF="C:Program Filesxpdfpdftotext.exe";
String filename="c:a.pdf";
String[] cmd = new String[] { PATH_TO_XPDF, "-enc", "UTF-8", "-q", filename, "-"};
Process p = Runtime.getRuntime().exec(cmd);
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
InputStreamReader reader = new InputStreamReader(bis, "UTF-8");
StringWriter out = new StringWriter();
char [] buf = new char[10000];
int len;
while((len = reader.read(buf))>= 0) {
//out.write(buf, 0, len);
System.out.println("the length is"+len);
}
reader.close();
String ts=new String(buf);
System.out.println("the str is"+ts);
}
}
展开全部
环境准备
txt利用common-io
pdf利用pdfbox
剩下的用POI
关于POI,读取xls没啥特别的,主要是读取doc和ppt,
需要下载poi源代码,然后将poi-src-3.7-20101029.zip\poi-3.7\src\scratchpad\src下的所有文件copy到工程,或者自己封装个jar包
jar包依赖
code如下:
package test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.NumberFormat;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;
public class ReadFileUtils {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ReadFileUtils rf = new ReadFileUtils();
String s = "";
// s = rf.readTXT("E:/itsm文档的后缀名分析报告2.txt");
// s = rf.readPDF("E:/memcached全面剖析.pdf");
// s = rf.readEXCEL("E:/副本工作量及成本模板.xls");
// s = rf.readEXCEL2007("E:/功能点估算方案.xlsx");
// s = rf.readWORD("E:/pms中文.doc");
// s = rf.readWORD2007("E:/功能点估算方法.docx");
//s = rf.readPPT("E:/精细化管理信息系统项目汇报v1.0.ppt");
s = rf.readPPT2007("e:/精细化管理信息系统项目汇报v1.0.pptx");
System.out.println(s);
}
// 读取ppt
public String readPPT(String file) throws IOException {
StringBuilder sb = new StringBuilder();
SlideShow ppt = new SlideShow(new HSLFSlideShow(file));
Slide[] slides = ppt.getSlides();
//提取文本信息
for (Slide each : slides) {
TextRun[] textRuns = each.getTextRuns();
for (int i=0 ;i< textRuns.length; i++ ) {
RichTextRun[] richTextRuns = textRuns.getRichTextRuns();
for (int j = 0; j < richTextRuns.length; j++) {
sb.append(richTextRuns[j].getText());
}
sb.append("\n");
}
sb.append("\n");
}
return sb.toString();
}
// 读取pptx
public String readPPT2007(String file) throws IOException, XmlException, OpenXML4JException {
return new XSLFPowerPointExtractor(POIXMLDocument.openPackage(file)).getText();
}
// 读取xls文件
public String readEXCEL(String file) throws IOException {
StringBuilder content = new StringBuilder();
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));// 创建对Excel工作簿文件的引用
for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
if (null != workbook.getSheetAt(numSheets)) {
HSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet
for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet
.getLastRowNum(); rowNumOfSheet++) {
if (null != aSheet.getRow(rowNumOfSheet)) {
HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一个行
for (short cellNumOfRow = 0; cellNumOfRow <= aRow
.getLastCellNum(); cellNumOfRow++) {
if (null != aRow.getCell(cellNumOfRow)) {
HSSFCell aCell = aRow.getCell(cellNumOfRow);// 获得列值
if (this.convertCell(aCell).length() > 0) {
content.append(this.convertCell(aCell));
}
}
content.append("\n");
}
}
}
}
}
return content.toString();
}
// 读取xlsx文件
public String readEXCEL2007(String file) throws IOException {
StringBuilder content = new StringBuilder();
XSSFWorkbook workbook = new XSSFWorkbook(file);
for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
if (null != workbook.getSheetAt(numSheets)) {
XSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet
for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet
.getLastRowNum(); rowNumOfSheet++) {
if (null != aSheet.getRow(rowNumOfSheet)) {
XSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一个行
for (short cellNumOfRow = 0; cellNumOfRow <= aRow
.getLastCellNum(); cellNumOfRow++) {
if (null != aRow.getCell(cellNumOfRow)) {
XSSFCell aCell = aRow.getCell(cellNumOfRow);// 获得列值
if (this.convertCell(aCell).length() > 0) {
content.append(this.convertCell(aCell));
}
}
content.append("\n");
}
}
}
}
}
return content.toString();
}
private String convertCell(Cell cell) {
NumberFormat formater = NumberFormat.getInstance();
formater.setGroupingUsed(false);
String cellValue = "";
if (cell == null) {
return cellValue;
}
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
cellValue = formater.format(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.valueOf(cell.getBooleanCellValue()).toString();
break;
case HSSFCell.CELL_TYPE_ERROR:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
default:
cellValue = "";
}
return cellValue.trim();
}
// 读取pdf文件
public String readPDF(String file) throws IOException {
String result = null;
FileInputStream is = null;
PDDocument document = null;
try {
is = new FileInputStream(file);
PDFParser parser = new PDFParser(is);
parser.parse();
document = parser.getPDDocument();
PDFTextStripper stripper = new PDFTextStripper();
result = stripper.getText(document);
} finally {
if (is != null) {
is.close();
}
if (document != null) {
document.close();
}
}
return result;
}
// 读取doc文件
public String readWORD(String file) throws Exception {
String returnStr = "";
try {
WordExtractor wordExtractor = new WordExtractor(new FileInputStream(new File(file)));
returnStr = wordExtractor.getText();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return returnStr;
}
// 读取docx文件
public String readWORD2007(String file) throws Exception {
return new XWPFWordExtractor(POIXMLDocument.openPackage(file)).getText();
}
// 读取txt文件
public String readTXT(String file) throws IOException {
String encoding = ReadFileUtils.get_charset(new File(file));
if (encoding.equalsIgnoreCase("GBK")) {
return FileUtils.readFileToString(new File(file), "gbk");
} else {
return FileUtils.readFileToString(new File(file), "utf8");
}
}
private static String get_charset(File file) throws IOException {
String charset = "GBK";
byte[] first3Bytes = new byte[3];
BufferedInputStream bis = null;
try {
boolean checked = false;
bis = new BufferedInputStream(new FileInputStream(file));
bis.mark(0);
int read = bis.read(first3Bytes, 0, 3);
if (read == -1)
return charset;
if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
charset = "UTF-16LE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE
&& first3Bytes[1] == (byte) 0xFF) {
charset = "UTF-16BE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xEF
&& first3Bytes[1] == (byte) 0xBB
&& first3Bytes[2] == (byte) 0xBF) {
charset = "UTF-8";
checked = true;
}
bis.reset();
if (!checked) {
// int len = 0;
int loc = 0;
while ((read = bis.read()) != -1) {
loc++;
if (read >= 0xF0)
break;
if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
break;
if (0xC0 <= read && read <= 0xDF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
// (0x80
// - 0xBF),也可能在GB编码内
continue;
else
break;
} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
charset = "UTF-8";
break;
} else
break;
} else
break;
}
}
// System.out.println( loc + " " + Integer.toHexString( read )
// );
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
}
return charset;
}
}
txt利用common-io
pdf利用pdfbox
剩下的用POI
关于POI,读取xls没啥特别的,主要是读取doc和ppt,
需要下载poi源代码,然后将poi-src-3.7-20101029.zip\poi-3.7\src\scratchpad\src下的所有文件copy到工程,或者自己封装个jar包
jar包依赖
code如下:
package test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.NumberFormat;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;
public class ReadFileUtils {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ReadFileUtils rf = new ReadFileUtils();
String s = "";
// s = rf.readTXT("E:/itsm文档的后缀名分析报告2.txt");
// s = rf.readPDF("E:/memcached全面剖析.pdf");
// s = rf.readEXCEL("E:/副本工作量及成本模板.xls");
// s = rf.readEXCEL2007("E:/功能点估算方案.xlsx");
// s = rf.readWORD("E:/pms中文.doc");
// s = rf.readWORD2007("E:/功能点估算方法.docx");
//s = rf.readPPT("E:/精细化管理信息系统项目汇报v1.0.ppt");
s = rf.readPPT2007("e:/精细化管理信息系统项目汇报v1.0.pptx");
System.out.println(s);
}
// 读取ppt
public String readPPT(String file) throws IOException {
StringBuilder sb = new StringBuilder();
SlideShow ppt = new SlideShow(new HSLFSlideShow(file));
Slide[] slides = ppt.getSlides();
//提取文本信息
for (Slide each : slides) {
TextRun[] textRuns = each.getTextRuns();
for (int i=0 ;i< textRuns.length; i++ ) {
RichTextRun[] richTextRuns = textRuns.getRichTextRuns();
for (int j = 0; j < richTextRuns.length; j++) {
sb.append(richTextRuns[j].getText());
}
sb.append("\n");
}
sb.append("\n");
}
return sb.toString();
}
// 读取pptx
public String readPPT2007(String file) throws IOException, XmlException, OpenXML4JException {
return new XSLFPowerPointExtractor(POIXMLDocument.openPackage(file)).getText();
}
// 读取xls文件
public String readEXCEL(String file) throws IOException {
StringBuilder content = new StringBuilder();
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));// 创建对Excel工作簿文件的引用
for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
if (null != workbook.getSheetAt(numSheets)) {
HSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet
for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet
.getLastRowNum(); rowNumOfSheet++) {
if (null != aSheet.getRow(rowNumOfSheet)) {
HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一个行
for (short cellNumOfRow = 0; cellNumOfRow <= aRow
.getLastCellNum(); cellNumOfRow++) {
if (null != aRow.getCell(cellNumOfRow)) {
HSSFCell aCell = aRow.getCell(cellNumOfRow);// 获得列值
if (this.convertCell(aCell).length() > 0) {
content.append(this.convertCell(aCell));
}
}
content.append("\n");
}
}
}
}
}
return content.toString();
}
// 读取xlsx文件
public String readEXCEL2007(String file) throws IOException {
StringBuilder content = new StringBuilder();
XSSFWorkbook workbook = new XSSFWorkbook(file);
for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
if (null != workbook.getSheetAt(numSheets)) {
XSSFSheet aSheet = workbook.getSheetAt(numSheets);// 获得一个sheet
for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet
.getLastRowNum(); rowNumOfSheet++) {
if (null != aSheet.getRow(rowNumOfSheet)) {
XSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一个行
for (short cellNumOfRow = 0; cellNumOfRow <= aRow
.getLastCellNum(); cellNumOfRow++) {
if (null != aRow.getCell(cellNumOfRow)) {
XSSFCell aCell = aRow.getCell(cellNumOfRow);// 获得列值
if (this.convertCell(aCell).length() > 0) {
content.append(this.convertCell(aCell));
}
}
content.append("\n");
}
}
}
}
}
return content.toString();
}
private String convertCell(Cell cell) {
NumberFormat formater = NumberFormat.getInstance();
formater.setGroupingUsed(false);
String cellValue = "";
if (cell == null) {
return cellValue;
}
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
cellValue = formater.format(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.valueOf(cell.getBooleanCellValue()).toString();
break;
case HSSFCell.CELL_TYPE_ERROR:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
default:
cellValue = "";
}
return cellValue.trim();
}
// 读取pdf文件
public String readPDF(String file) throws IOException {
String result = null;
FileInputStream is = null;
PDDocument document = null;
try {
is = new FileInputStream(file);
PDFParser parser = new PDFParser(is);
parser.parse();
document = parser.getPDDocument();
PDFTextStripper stripper = new PDFTextStripper();
result = stripper.getText(document);
} finally {
if (is != null) {
is.close();
}
if (document != null) {
document.close();
}
}
return result;
}
// 读取doc文件
public String readWORD(String file) throws Exception {
String returnStr = "";
try {
WordExtractor wordExtractor = new WordExtractor(new FileInputStream(new File(file)));
returnStr = wordExtractor.getText();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return returnStr;
}
// 读取docx文件
public String readWORD2007(String file) throws Exception {
return new XWPFWordExtractor(POIXMLDocument.openPackage(file)).getText();
}
// 读取txt文件
public String readTXT(String file) throws IOException {
String encoding = ReadFileUtils.get_charset(new File(file));
if (encoding.equalsIgnoreCase("GBK")) {
return FileUtils.readFileToString(new File(file), "gbk");
} else {
return FileUtils.readFileToString(new File(file), "utf8");
}
}
private static String get_charset(File file) throws IOException {
String charset = "GBK";
byte[] first3Bytes = new byte[3];
BufferedInputStream bis = null;
try {
boolean checked = false;
bis = new BufferedInputStream(new FileInputStream(file));
bis.mark(0);
int read = bis.read(first3Bytes, 0, 3);
if (read == -1)
return charset;
if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
charset = "UTF-16LE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE
&& first3Bytes[1] == (byte) 0xFF) {
charset = "UTF-16BE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xEF
&& first3Bytes[1] == (byte) 0xBB
&& first3Bytes[2] == (byte) 0xBF) {
charset = "UTF-8";
checked = true;
}
bis.reset();
if (!checked) {
// int len = 0;
int loc = 0;
while ((read = bis.read()) != -1) {
loc++;
if (read >= 0xF0)
break;
if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
break;
if (0xC0 <= read && read <= 0xDF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
// (0x80
// - 0xBF),也可能在GB编码内
continue;
else
break;
} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
charset = "UTF-8";
break;
} else
break;
} else
break;
}
}
// System.out.println( loc + " " + Integer.toHexString( read )
// );
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
}
return charset;
}
}
追问
这个还是一样,只能读取文本,不能读取图片。
读pdf时还报错。
Exception in thread "main" java.io.IOException: Unknown encoding for 'UniGB-UCS2-H'
at org.pdfbox.encoding.EncodingManager.getEncoding(EncodingManager.java:83)
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询