用户登录
用户注册

分享至

word文件解析java java读取word文件内容

  • 作者: 沈阳的大叔
  • 来源: 51数据库
  • 2020-04-15

word文件解析java

java解析word文档有哪些方法

java读取word文档时,虽然网上介绍了很多插件poi、java2Word、jacob、itext等等,poi无法读取格式(新的API估计行好像还在处于研发阶段,不太稳定,做项目不太敢用);java2Word、jacob容易报错找不到注册,比较诡异,我曾经在不同的机器上试过,操作方法完全一致,有的机器不报错,有的报错,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关于读的好办法。

经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式,不需要借助任何插件,只需基本IO操作外加编码转换即可。

rtf格式文件表面看来和doc没啥区别,都可以用word打开,各种格式都可以设定。

----- 实现的功能:读取rtf模板内容(格式和文本内容),替换变化部分,形成新的rtf文档。

----- 实现思路:模板中固定部分手动输入,变化的部分用$info$表示,只需替换$info$即可。

1、采用字节的形式读取rtf模板内容2、将可变的内容字符串转为rtf编码3、替换原文中的可变部分,形成新的rtf文档主要程序如下:public String bin2hex(String bin) {char[] digital = "0123456789ABCDEF".toCharArray();StringBuffer sb = new StringBuffer("");byte[] bs = bin.getBytes();int bit;for (int i = 0; i > 4;sb.append("\\'");sb.append(digital[bit]);bit = bs[i] & 0x0f;sb.append(digital[bit]);}return sb.toString(); }public String readByteRtf(InputStream ins, String path){ String sourcecontent =""; try{ ins = newFileInputStream(path); byte[] b= new byte[1024];if (ins == null) {System.out.println("源模板文件不存在");}int bytesRead = 0;while (true) {bytesRead = ins.read(b, 0, 1024); // return final read bytescountsif(bytesRead == -1) {// end of InputStreamSystem.out.println("读取模板文件结束");break;}sourcecontent += new String(b, 0, bytesRead); // convert to stringusing bytes} }catch(Exception e){ e.printStackTrace(); } return sourcecontent ;}以上为核心代码,剩余部分就是替换,从新组装java中的String.replace(oldstr,newstr);方法可以实现,在这就不贴了。

源代码部分详见附件。

运行源代码前提:c盘创建YQ目录,将附件中"模板.rtf"复制到YQ目录之下,运行OpreatorRTF.java文件即可,就会在YQ目录下生成文件名如:21时15分19秒_cheney_记录.rtf的文件。

package com;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;public class OperatorRTF {public String strToRtf(String content){char[] digital = "0123456789ABCDEF".toCharArray();StringBuffer sb = new StringBuffer("");byte[] bs = content.getBytes();int bit;for (int i = 0; i > 4;sb.append("\\'");sb.append(digital[bit]);bit = bs[i] & 0x0f;sb.append(digital[bit]);}return sb.toString();}public String replaceRTF(String content,String replacecontent,intflag){String rc = strToRtf(replacecontent);String target = "";if(flag==0){target = content.replace("$timetop$",rc);}if(flag==1){target = content.replace("$info$",rc);}if(flag==2){target = content.replace("$idea$",rc);}if(flag==3){target = content.replace("$advice$",rc);}if(flag==4){target = content.replace("$infosend$",rc);}return target;}public String getSavePath() {String path = "C:\\YQ";File fDirecotry = new File(path);if (!fDirecotry.exists()) {fDirecotry.mkdirs();}return path;}public String ToSBC(String input){char[] c =input.toCharArray();for (int i =0; i < c.length; i++){if (c[i] == 32){c[i] = (char) 12288;continue;}if (c[i] < 127){c[i] = (char) (c[i] + 65248);}}return newString(c);}public void rgModel(String username, String content) {// TODO Auto-generated method stubDate current=new Date();SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-ddHH:mm:ss");String targetname = sdf.format(current).substring(11,13) + "时";targetname += sdf.format(current).substring(14,16) + "分";targetname += sdf.format(current).substring(17,19) + "秒";targetname += "_" + username +"_记录.rtf";String strpath = getSavePath();String sourname = strpath+"\\"+"模板.rtf";String sourcecontent = "";InputStream ins = null;try{ins = new FileInputStream(sourname);byte[] b = new byte[1024];if (ins == null) {System.out.println("源模板文件不存在");}int bytesRead = 0;while (true) {bytesRead = ins.read(b, 0, 1024); // return final read bytescountsif(bytesRead == -1) {// end of InputStreamSystem.out.println("读取模板文件结束");break;}sourcecontent += new Strin...

java读取word文件的问题

请贴出代码,谢谢。

请关闭输入流,释放资源,谢谢。

调用close()方法。

其他貌似没有发现什么问题。

public static String run(String filename){WordExtractor extractor=null;String text=null;try{FileInputStream in = new FileInputStream (filename);extractor = new WordExtractor();text=extractor.extractText(in);}catch(Exception ex){//logreturn null;}return text;}public static void main(String[] args){try{FileOutputStream out=new FileOutputStream("result.txt");out.write(WordProcess.run(args[0]).getBytes());out.flush();out.close();}catch(Exception ex){System.out.println(ex.toString());}}看看这个。

模范这样写,试试看。

这个代码我试过,没问题,如果这样写还是有问题,那就不是代码的问题了。

Java 解析Word文档简历

aco是Java和Windows下的Com桥,通过它我们可以在Java程序中调用COM组件。

如果你的JDK是1.4,那你需要下载Jaco 1.9的jni库才能正常运行,早期版本在JDK 1.4下有些问题。

以下是引用片段:package com;*** 〈p〉Title:Wod文档转html类〈p〉* 〈p〉Desciption: 〈p〉* 〈p〉Copyight:() 2002〈p〉* @autho 舵手* @vesion 1.0*impot com.jaco.com.*;impot com.jaco.activeX.*;pulic class WodtoHtml {***文档转换函数*@paam docfile wod文档的绝对路径加文件名(包含扩展名)*@paam htmlfile 转换后的html文件绝对路径和文件名(不含扩展名)*pulic static void change(Sting docfile, Sting htmlfile) {ActiveXComponent app = new ActiveXComponent("Wod.Application"); 启动wodty {app.setPopety("Visile", new Vaiant(false));设置wod不可见Oject docs = app.getPopety("Documents").toDispatch();Oject doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Oject[]{ docfile, new Vaiant(false),new Vaiant(tue) }, new int[1]).toDispatch(); 打开wod文件Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Oject[] {htmlfile,new Vaiant (8) }, new int[1]); 作为html格式保存到临时文件Vaiant f = new Vaiant(false);Dispatch.call(doc, "Close", f);} catch (Exception e) {e.pintStackTace();} finally {app.invoke("Quit", new Vaiant[]{});}}pulic static void main(Sting[] sts){WodtoHtml.change("c:\\a\\运输管理调度系统总体方案.doc", "c:\\a\\t");}}

JAVA读取WORD,EXCEL,PDF文件的方法是什么呢?

JAVA读取WORD,EXCEL,POWERPOINT,PDF文件的方法 OFFICE文档使用POI控件,PDF可以使用PDFBOX0.7.3控件,完全支持中文,用XPDF也行,不过感觉PDFBOX比较好,而且作者也在更新。

水平有限,万望各位指正 WORD: import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.poi.hwpf.extractor.WordExtractor; import java.io.File; import java.io.InputStream; import java.io.FileInputStream; import com.search.code.Index; public Document getDocument(Index index, String url, String title, InputStream is) throws DocCenterException { String bodyText = null; try { WordExtractor ex = new WordExtractor(is);//is是WORD文件的InputStream bodyText = ex.getText(); if(!bodyText.equals("")){ index.AddIndex(url, title, bodyText); } }catch (DocCenterException e) { throw new DocCenterException("无法从该Mocriosoft Word文档中提取内容", e); }catch(Exception e){ e.printStackTrace(); } } return null; } Excel: import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFCell; import java.io.File; import java.io.InputStream; import java.io.FileInputStream; import com.search.code.Index; public Document getDocument(Index index, String url, String title, InputStream is) throws DocCenterException { StringBuffer content = new StringBuffer(); try{

JAVA中如何把WORD文档直接转换成html?

jaco是java和windows下的com桥,通过它我们可以在java程序中调用COM组件。

如果你的JDK是1.4,那你需要下载jaco1.9的jni库才能正常运行,早期版本在JDK1.4下有些问题。

package com;** * Title:Wod文档转html类 * Desciption: * Copyight:() 2002 * @autho 舵手 * @vesion 1.0 *impot com.jaco.com.*;impot com.jaco.activeX.*; pulic class WodtoHtml { ** *文档转换函数 *@paam docfile wod文档的绝对路径加文件名(包含扩展名) *@paam htmlfile 转换后的html文件绝对路径和文件名(不含扩展名) * pulic static void change(Sting docfile, Sting htmlfile) { ActiveXComponent app = new ActiveXComponent("Wod.Application"); 启动wod ty { app.setPopety("Visile", new Vaiant(false)); 设置wod不可见 Oject docs = app.getPopety("Documents").toDispatch(); Oject doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Oject[] { docfile, new Vaiant(false),new Vaiant(tue) }, new int[1]).toDispatch(); 打开wod文件 Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Oject[] {htmlfile, new Vaiant(8) }, new int[1]); 作为html格式保存到临时文件 Vaiant f = new Vaiant(false); Dispatch.call(doc, "Close", f); } catch (Exception e) { e.pintStackTace(); } finally { app.invoke("Quit", new Vaiant[]{}); } } pulic static void main(Sting[] sts){ WodtoHtml.change("c:\\a\\运输管理调度系统总体方案.doc", "c:\\a\\t"); }}

如何用java解析bin文件?

public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

*/ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读一个字节 in = new FileInputStream(file); int tempbyte; while ((tempbyte = in.read()) != -1) { System.out.write(tempbyte); } in.close(); } catch (IOException e) { e.printStackTrace(); return; } try { System.out.println("以字节为单位读取文件内容,一次读多个字节:"); // 一次读多个字节 byte[] tempbytes = new byte[100]; int byteread = 0; in = new FileInputStream(fileName); ReadFromFile.showAvailableBytes(in); // 读入多个字节到字节数组中,byteread为一次读入的字节数 while ((byteread = in.read(tempbytes)) != -1) { System.out.write(tempbytes, 0, byteread); } } catch (Exception e1) { e1.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e1) { } } } } /** * 以字符为单位读取文件,常用于读文本,数字等类型的文件 */ public static void readFileByChars(String fileName) { File file = new File(fileName); Reader reader = null; try { System.out.println("以字符为单位读取文件内容,一次读一个字节:"); // 一次读一个字符 reader = new InputStreamReader(new FileInputStream(file)); int tempchar; while ((tempchar = reader.read()) != -1) { // 对于windows下,\r\n这两个字符在一起时,表示一个换行。

// 但如果这两个字符分开显示时,会换两次行。

// 因此,屏蔽掉\r,或者屏蔽\n。

否则,将会多出很多空行。

if (((char) tempchar) != '\r') { System.out.print((char) tempchar); } } reader.close(); } catch (Exception e) { e.printStackTrace(); } try { System.out.println("以字符为单位读取文件内容,一次读多个字节:"); // 一次读多个字符 char[] tempchars = new char[30]; int charread = 0; reader = new InputStreamReader(new FileInputStream(fileName)); // 读入多个字符到字符数组中,charread为一次读取字符数 while ((charread = reader.read(tempchars)) != -1) { // 同样屏蔽掉\r不显示 if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != '\r')) { System.out.print(tempchars); } else { for (int i = 0; i if (tempchars[i] == '\r') { continue; } else { System.out.print(tempchars[i]); } } } } } catch (Exception e1) { e1.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } /** * 以行为单位读取文件,常用于读面向行的格式化文件 */ public static void readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } }你参考下把

如何用JAVA解析txt文件

判断文件是否存在InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);/);}read;\res\\.BufferedInputStream;读取文件内容出错&quot.Reader; public class H20121012 {/*** 功能.println("20121012.txt";File file=new File(filePath),需要读取生成字节流* 4:一行一行的输出。

readline()。

接下来需要解读成乙方可以理解的东西既然你使用了FileInputStream()。

那么对应的需要使用InputStreamReader()这个方法进行解读刚才装进来内存当中的数据解读完成后要输出呀。

那当然要转换成IO可以识别的数据呀。

那就需要调用字节码读取的方法BufferedReader():获得文件句柄当做是输入一个字节码流;}}public static void main(String argv[]){String filePath = "L:\。

* 备注:需要考虑的是异常情况* @param filePath*/public static void readTxtFile(String filePath){try {String encoding="GBK&quot,需要对这个输入流进行读取* 3.io.File.close();/考虑到编码格式BufferedReader bufferedReader = new BufferedReader(read);String lineTxt = null;while((lineTxt = bufferedReader.readLine()) ;\htdocs\ import java.io。

同时使用bufferedReader()的readline()方法读取txt文件中的每一行数据哈。

package com.campu;import java.io; import java.io.FileInputStream.out;\Apache\readTxtFile(filePath);e; "res/".printStackTrace(); import java.io.isFile() && file.exists()){ //.BufferedReader; import java:Java读取txt文件的内容* 步骤:1:先获得文件句柄* 2;if(file:读取到输入流后;}else{System.out.println("找不到指定的文件");}} catch (Exception e) {System.InputStreamReader;; //java读取txt文件内容。

可以作如下理解:首先获得一个文件句柄。

File file = new File(); file即为文件句柄。

两人之间连通电话网络了。

接下来可以开始打电话了。

通过这条线路读取甲方的信息:new FileInputStream(file) 目前这个信息已经读进来内存当中了!= null){System.out.println(lineTxt); import java.io

Java如何操作Word,Excel,PDF文档?

Java Excel API 文档 http://www.andykhan.com/jexcelapi/ 1、一个jacob操作Word的例子,其他操作excel,pdf的sample里都有 import java.io.File; import com.jacob.com.*; import com.jacob.activeX.*; public class WordTest { public static void main(String[] args) { WordBean word=new WordBean(); word.openWord(true); word.createNewDocument(); word.insertText("Hello word."); } } import com.jacob.activeX.*; import com.jacob.com.*; public class WordBean extends java.awt.Panel { private ActiveXComponent MsWordApp = null; private Dispatch document = null; public WordBean() { super(); } public void openWord(boolean makeVisible) { //Open Word if we've not done it already if (MsWordApp == null) { MsWordApp = new ActiveXComponent("Word.Application"); } //Set the visible property as required. Dispatch.put(MsWordApp, "Visible", new Variant(makeVisible)); } public void createNewDocument() { //Find the Documents collection object maintained by Word Dispatch documents = Dispatch.get(MsWordApp,"Documents").toDispatch(); //Call the Add method of the Documents collection to create //a new document to edit document = Dispatch.call(documents,"Add").toDispatch(); } public void insertText(String textToInsert) { // Get the current selection within Word at the moment. If // a new document has just been created then this will be at // the top of the new doc Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch(); //Put the specified text at the insertion point Dispatch.put(selection,"Text",textToInsert); } public void saveFileAs(String filename) { Dispatch.call(document,"SaveAs",filename); } public void printFile() { //Just print the current document to the default printer Dispatch.call(document,"PrintOut"); } public void closeDocument() { // Close the document without saving changes // 0 = wdDoNotSaveChanges // -1 = wdSaveChanges // -2 = wdPromptToSaveChanges Dispatch.call(document, "Close", new Variant(0)); document = null; } public void closeWord() { Dispatch.call(MsWordApp,"Quit"); MsWordApp = null; document = null; } }

转载请注明出处51数据库 » word文件解析java

软件
前端设计
程序设计
Java相关