java讀取doc文本,java讀取doc文件內容

本文目錄一覽:

java讀取word文件的內容

WordExtractor的用法錯了,你用下面的方法試試:

……

File file = new File(doc);

FileInputStream fileInputStream = getFileInputStream(file);

WordExtractor wordExtractor = new WordExtractor(fileInputStream);

String text = wordExtractor.getText();

……

java讀取帶格式word內容

用jacob吧。。

/**

*@author eyuan

*/

package per.eyuan.word2txt.core;

import com.jacob.*;

import com.jacob.com.*;

import com.jacob.activeX.*;

import java.io.*;

import java.util.Scanner;

public class Core {

/**

* 實現轉換的函數

* @param sourceFilesPath

* @param destinationFilesPath

* @param destinationFilesType

* @return void

* @see import com.jacob.activeX.*;

*/

public static void change(String sourceFilesPath,String destinationFilesPath,int destinationFilesType){

//使用word文件所在的目錄(源路徑)建立目錄文件

File sourcePathFile=new File(sourceFilesPath);

//取得word文件(源文件列表)

File sourceFilesList[]=sourcePathFile.listFiles();

System.out.println(“共有”+sourceFilesList.length+”個文件(文件夾)”);

//指定要轉換的文件所在的目錄下,如果有子目錄,

//則進入子目錄,繼續查找word文檔並將其轉換,

//直到將指定目錄下的所有word文檔轉換完。

//子目錄名

String sourceChildPath=new String(“”);

//保持原來的層次關係,將子目錄下的文件存放在新建的子目錄中

String destiNationChildPath=new String(“”);

//檢索文件,過濾掉非word文件,通過擴展名過濾

for(int i=0;isourceFilesList.length;i++){

//排除掉子文件夾

if(sourceFilesList[i].isFile()){

System.out.println(“第”+(i+1)+”個文件:”);

//取得文件全名(包含擴展名)

String fileName=sourceFilesList[i].getName();

String fileType=new String(“”);

//取得文件擴展名

fileType=fileName.substring((fileName.length()-4), fileName.length());

//word2007-2010擴展名為docx

//判斷是否為word2007-2010文檔,及是否以docx為後綴名

if(fileType.equals(“docx”)){

System.out.println(“正在轉換。。。”);

//輸出word文檔所在路勁

System.out.println(“目錄:”+sourceFilesPath);

//輸出word文檔名

System.out.println(“文件名:”+fileName);

//System.out.println(fileName.substring(0, (fileName.length()-5)));

//核心函數

//啟動word

ActiveXComponent app=new ActiveXComponent(“Word.Application”);

//要轉換的文檔的全路徑(所在文件夾+文件全名)

String docPath=sourceFilesPath+”\\”+fileName;

//轉換後的文檔的全路徑(所在文件夾+文件名)

String othersPath=destinationFilesPath+”\\”+fileName.substring(0,(fileName.length()-5));

//

String inFile=docPath;

String outFile=othersPath;

//

boolean flag=false;

//核心代碼

try{

//設置word可見性

app.setProperty(“Visible”, new Variant(false));

//

Dispatch docs=app.getProperty(“Documents”).toDispatch();

//打開word文檔

Dispatch doc=Dispatch.invoke(docs, “Open”, Dispatch.Method, new Object[]{inFile,new Variant(false),new Variant(true)}, new int[1]).toDispatch();

//0:Microsoft Word 97 – 2003 文檔 (.doc)

//1:Microsoft Word 97 – 2003 模板 (.dot)

//2:文本文檔 (.txt)

//3:文本文檔 (.txt)

//4:文本文檔 (.txt)

//5:文本文檔 (.txt)

//6:RTF 格式 (.rtf)

//7:文本文檔 (.txt)

//8:HTML 文檔 (.htm)(帶文件夾)

//9:MHTML 文檔 (.mht)(單文件)

//10:MHTML 文檔 (.mht)(單文件)

//11:XML 文檔 (.xml)

//12:Microsoft Word 文檔 (.docx)

//13:Microsoft Word 啟用宏的文檔 (.docm)

//14:Microsoft Word 模板 (.dotx)

//15:Microsoft Word 啟用宏的模板 (.dotm)

//16:Microsoft Word 文檔 (.docx)

//17:PDF 文件 (.pdf)

//18:XPS 文檔 (.xps)

//19:XML 文檔 (.xml)

//20:XML 文檔 (.xml)

//21:XML 文檔 (.xml)

//22:XML 文檔 (.xml)

//23:OpenDocument 文本 (.odt)

//24:WTF 文件 (.wtf)

//另存為指定格式的文檔

Dispatch.invoke(doc, “SaveAs”, Dispatch.Method, new Object[]{outFile,new Variant(destinationFilesType)}, new int[1]);

//

Variant file=new Variant(false);

//關閉文檔

Dispatch.call(doc, “Close”,file);

//

flag=true;

}catch(Exception e){

e.printStackTrace();

System.out.println(“文檔轉換失敗”);

}finally{

app.invoke(“Quit”,new Variant[]{});

}

System.out.println(“轉換完畢”);

}

//word97-2003擴展名為doc

//判斷是否為word2003-2007文檔,及是否以doc為後綴名

else if(fileType.equals(“.doc”)){

System.out.println(“正在轉換。。。”);

//輸出word文檔所在路勁

System.out.println(“目錄:”+sourceFilesPath);

//輸出word文檔名

System.out.println(“文件名:”+fileName);

//System.out.println(fileName.substring(0, (fileName.length()-4)));

//核心函數

//啟動word

ActiveXComponent app=new ActiveXComponent(“Word.Application”);

//要轉換的文檔的全路徑(所在文件夾+文件全名)

String docPath=sourceFilesPath+”\\”+fileName;

//轉換後的文檔的全路徑(所在文件夾+文件名)

String othersPath=destinationFilesPath+”\\”+fileName.substring(0,(fileName.length()-4));

//

String inFile=docPath;

String outFile=othersPath;

//

boolean flag=false;

//核心代碼

try{

//設置word可見性

app.setProperty(“Visible”, new Variant(false));

//

Dispatch docs=app.getProperty(“Documents”).toDispatch();

//打開word文檔

Dispatch doc=Dispatch.invoke(docs, “Open”, Dispatch.Method, new Object[]{inFile,new Variant(false),new Variant(true)}, new int[1]).toDispatch();

//另存為指定格式的文檔

Dispatch.invoke(doc, “SaveAs”, Dispatch.Method, new Object[]{outFile,new Variant(destinationFilesType)}, new int[1]);

//

Variant file=new Variant(false);

//關閉文檔

Dispatch.call(doc, “Close”,file);

//

flag=true;

}catch(Exception e){

e.printStackTrace();

System.out.println(“文檔轉換失敗”);

}finally{

app.invoke(“Quit”,new Variant[]{});

}

System.out.println(“轉換完畢”);

}

//文檔的擴展名不是doc或docx

else{

System.out.println(“非word文檔”);

}

}

//如果是子文件夾,則遞歸遍歷,將所有的word文檔轉換

else{

//

sourceChildPath=sourceFilesPath;

//該文件是目錄

sourceChildPath=sourceChildPath+”\\”+sourceFilesList[i].getName()+”\\”;

System.out.println(“源文件所在路徑:”+sourceChildPath);

//修改目標文件夾,保持原來的層級關係

destiNationChildPath=destinationFilesPath;

destiNationChildPath=destinationFilesPath+”\\”+sourceFilesList[i].getName()+”\\”;

System.out.println(“轉換後文件所在路徑”+destiNationChildPath);

//

mkdir(destiNationChildPath);

//遞歸遍歷所有目錄,查找word文檔,並將其轉換

change(sourceChildPath, destiNationChildPath,destinationFilesType);

}

}

System.out.println(“所有文檔轉換完畢”);

}

/**

 * 用於創建文件夾的方法

 * @param mkdirName

 */

public static void mkdir(String mkdirName){

try{

//使用指定的路徑創建文件對象

File dirFile = new File(mkdirName);

//

boolean bFile = dirFile.exists();

//已經存在文件夾,操作???提醒是否要替換

if( bFile == true ) {

System.out.println(“已經存在文件夾”+mkdirName);

}

//不存在該文件夾,則新建該目錄

else{

System.out.println(“新建文件夾”+mkdirName);

bFile = dirFile.mkdir();

if( bFile == true ){

System.out.println(“文件夾創建成功”);

}else{

System.out.println(” 文件夾創建失敗,清確認磁碟沒有防寫並且空件足夠”);

System.exit(1);

}

}

}catch(Exception err){

System.err.println(“ELS – Chart : 文件夾創建發生異常”);

err.printStackTrace();

}finally{

}

}

/**

* 判斷某個文件夾是否存在

* @param path

*/

public static boolean isPathExist(String path){

boolean isPathExist=false;

try{

File pathFile = new File(path);

if(pathFile.exists())

isPathExist= true;

else

isPathExist= false;

}catch(Exception err){

err.printStackTrace();

}

return isPathExist;

}

/**

* 主函數

*/

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

//源文檔所在路徑

String sourceFilesPath=””;

// String inputSourcePath=””;

// boolean sourcePathFlag=true;

// System.out.println(“請輸入要轉換文檔所在的文件夾”);

// while(sourcePathFlag){

// inputSourcePath=sc.next();

// if(!isPathExist(inputSourcePath))

// System.out.println(“源路徑不存在,請輸入正確的路徑”);

// else

// sourcePathFlag=false;

// }

// sourceFilesPath=inputSourcePath;

sourceFilesPath=”D:\\word”;

//目標文檔要存放的目錄

String destinationFilesPath=””;

// String inputdestinationPath=””;

// boolean destinationPathFlag=true;

// System.out.println(“請輸入轉換後文檔要存放的文件夾”);

// while(destinationPathFlag){

// inputdestinationPath=sc.next();

// //目標文件不存在時,是否要提示用戶創建文件

// if(!isPathExist(inputdestinationPath))

// System.out.println(“目標路徑不存在,請輸入正確的路徑”);

// else

// destinationPathFlag=false;

// }

// destinationFilesPath=inputdestinationPath;

destinationFilesPath=”D:\\txt”;

//選擇要轉換的類型

int destinationFilesType=0;

int inputNumber=0;

boolean numFlag=true;

System.out.println(“您要將word文檔轉換為哪種文檔格式?”);

System.out.println(“0:doc \t 2:txt \t 8:html \t 9:htm \t 11:xml \t 12:docx \t 17:pdf \t 18:xps”);

while(numFlag){

inputNumber=sc.nextInt();

if(inputNumber!=2inputNumber!=8inputNumber!=9inputNumber!=11inputNumber!=12inputNumber!=17){

System.out.println(“您的輸入有誤,請輸入要轉換的文檔類型前的數字”);

}else

numFlag=false;

}

destinationFilesType=inputNumber;

//實行轉換

change(sourceFilesPath, destinationFilesPath,destinationFilesType);

//測試各種類型轉換

// for(int i=0;i25;i++){

// destinationFilesType=i;

// System.out.println(“文件類型”+destinationFilesType);

// System.out.println(“存放目錄:”+destinationFilesPath+”\\”+i);

// mkdir(destinationFilesPath+”\\”+i);

// change(sourceFilesPath, destinationFilesPath+”\\”+i,destinationFilesType);

// }

}

}

這個我剛用的。。格式都能帶過來的。 你自己再下載個 jacob的包和dll文件

JAVA有什麼好的方法可以將word里的文本讀取出來

你用免費版的Free Spire.Doc for Java可以直接讀取Word文檔裡面的文本,參考代碼:

import com.spire.doc.Document;

import java.io.FileWriter;

import java.io.IOException;

public class ExtractText {

public static void main(String[] args) throws IOException {

//載入Word文檔

Document document = new Document();

document.loadFromFile(“C:\\Users\\Administrator\\Desktop\\sample.docx”);

//獲取文檔中的文本保存為String

String text=document.getText();

//將String寫入Txt文件

writeStringToTxt(text,”ExtractedText.txt”);

}

public static void writeStringToTxt(String content, String txtFileName) throws IOException {

FileWriter fWriter= new FileWriter(txtFileName,true);

try {

fWriter.write(content);

}catch(IOException ex){

ex.printStackTrace();

}finally{

try{

fWriter.flush();

fWriter.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

參考自官網原文。

java讀取doc,pdf問題。

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文件。

補丁包:

按照readme放好中文的patch,就可以開始寫調用本地方法的java程序了。

下面是一個如何調用的例子:

import java.io.*;  

/** 

* pTitle: pdf extraction/p 

* pDescription: email:chris@matrix.org.cn/p 

* pCopyright: Matrix Copyright (c) 2003/p 

* pCompany: 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);  

}  

}

如何使用JAVA,POI讀寫word文檔

public class HwpfTest {

@SuppressWarnings(“deprecation”)

@Test

public void testReadByExtractor() throws Exception {

InputStream is = new FileInputStream(“D:\\test.doc”);

WordExtractor extractor = new WordExtractor(is);

//輸出word文檔所有的文本

System.out.println(extractor.getText());

System.out.println(extractor.getTextFromPieces());

//輸出頁眉的內容

System.out.println(“頁眉:” + extractor.getHeaderText());

//輸出頁腳的內容

System.out.println(“頁腳:” + extractor.getFooterText());

//輸出當前word文檔的元數據信息,包括作者、文檔的修改時間等。

System.out.println(extractor.getMetadataTextExtractor().getText());

//獲取各個段落的文本

String paraTexts[] = extractor.getParagraphText();

for (int i=0; iparaTexts.length; i++) {

System.out.println(“Paragraph ” + (i+1) + ” : ” + paraTexts[i]);

}

//輸出當前word的一些信息

printInfo(extractor.getSummaryInformation());

//輸出當前word的一些信息

this.printInfo(extractor.getDocSummaryInformation());

this.closeStream(is);

}

/**

* 輸出SummaryInfomation

* @param info

*/

private void printInfo(SummaryInformation info) {

//作者

System.out.println(info.getAuthor());

//字元統計

System.out.println(info.getCharCount());

//頁數

System.out.println(info.getPageCount());

//標題

System.out.println(info.getTitle());

//主題

System.out.println(info.getSubject());

}

/**

* 輸出DocumentSummaryInfomation

* @param info

*/

private void printInfo(DocumentSummaryInformation info) {

//分類

System.out.println(info.getCategory());

//公司

System.out.println(info.getCompany());

}

/**

* 關閉輸入流

* @param is

*/

private void closeStream(InputStream is) {

if (is != null) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

java如何獲得doc文件內容

java 是這樣處理的 獲得一個 模板 +數據 = doc文件

反過來 doc文件 + 模板 可以得到 數據

如果你沒有 模板, 基本上是不行。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/243072.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 12:54
下一篇 2024-12-12 12:54

相關推薦

發表回復

登錄後才能評論