文檔解析java代碼,java源代碼解析

java解析pdf文件,求大神提供代碼,請注意是java語言的

給你提供一個參考例子,你可以在這個例子上試試,修改修改。也是解析PDF的。

創(chuàng)新互聯(lián)主營海勃灣網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,手機APP定制開發(fā),海勃灣h5小程序開發(fā)搭建,海勃灣網(wǎng)站營銷推廣歡迎海勃灣等地區(qū)企業(yè)咨詢

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.apache.pdfbox.pdmodel.PDDocument;

import?org.apache.pdfbox.util.PDFTextStripper;

public?class?PdfReader?{????

public?void?readFdf(String?file)?throws?Exception?{????

//?是否排序????

boolean?sort?=?false;????

//?pdf文件名????

String?pdfFile?=?file;????

//?輸入文本文件名稱????

String?textFile?=?null;????

//?編碼方式????

String?encoding?=?"UTF-8";????

//?開始提取頁數(shù)????

int?startPage?=?1;????

//?結(jié)束提取頁數(shù)????

int?endPage?=?Integer.MAX_VALUE;????

//?文件輸入流,生成文本文件????

Writer?output?=?null;????

//?內(nèi)存中存儲的PDF?Document????

PDDocument?document?=?null;????

try?{????

try?{????

//?首先當(dāng)作一個URL來裝載文件,如果得到異常再從本地文件系統(tǒng)//去裝載文件????

URL?url?=?new?URL(pdfFile);????

//注意參數(shù)已不是以前版本中的URL.而是File。????

document?=?PDDocument.load(pdfFile);????

//?獲取PDF的文件名????

String?fileName?=?url.getFile();????

//?以原來PDF的名稱來命名新產(chǎn)生的txt文件????

if?(fileName.length()??4)?{????

File?outputFile?=?new?File(fileName.substring(0,?fileName????

.length()?-?4)????

+?".txt");????

textFile?=?outputFile.getName();????

}????

}?catch?(MalformedURLException?e)?{????

//?如果作為URL裝載得到異常則從文件系統(tǒng)裝載????

//注意參數(shù)已不是以前版本中的URL.而是File。????

document?=?PDDocument.load(pdfFile);????

if?(pdfFile.length()??4)?{????

textFile?=?pdfFile.substring(0,?pdfFile.length()?-?4)????

+?".txt";????

}????

}????

//?文件輸入流,寫入文件倒textFile????

output?=?new?OutputStreamWriter(new?FileOutputStream(textFile),????

encoding);????

//?PDFTextStripper來提取文本????

PDFTextStripper?stripper?=?null;????

stripper?=?new?PDFTextStripper();????

//?設(shè)置是否排序????

stripper.setSortByPosition(sort);????

//?設(shè)置起始頁????

stripper.setStartPage(startPage);????

//?設(shè)置結(jié)束頁????

stripper.setEndPage(endPage);????

//?調(diào)用PDFTextStripper的writeText提取并輸出文本????

stripper.writeText(document,?output);????

}?finally?{????

if?(output?!=?null)?{????

//?關(guān)閉輸出流????

output.close();????

}????

if?(document?!=?null)?{????

//?關(guān)閉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的內(nèi)容????

pdfReader.readFdf("d:\\b.pdf");????

}?catch?(Exception?e)?{????

e.printStackTrace();????

}????

}????

}

用java如何解析pdf文件

一、前言

在企業(yè)的信息系統(tǒng)中,報表處理一直占比較重要的作用,本文將介紹一種生成PDF報表的Java組件--iText。通過在服務(wù)器端使用Jsp或JavaBean生成PDF報表,客戶端采用超級連接顯示或下載得到生成的報表,這樣就很好的解決了B/S系統(tǒng)的報表處理問題。

二、iText簡介

iText是著名的開放源碼的站點sourceforge一個項目,是用于生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉(zhuǎn)化為PDF文件。

iText的安裝非常方便,在 - download 網(wǎng)站上下載iText.jar文件后,只需要在系統(tǒng)的CLASSPATH中加入iText.jar的路徑,在程序中就可以使用iText類庫了。

三、建立第一個PDF文檔

用iText生成PDF文檔需要5個步驟:

①建立com.lowagie.text.Document對象的實例。

Document document = new Document();

②建立一個書寫器(Writer)與document對象關(guān)聯(lián),通過書寫器(Writer)可以將文檔寫入到磁盤中。

PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));

③打開文檔。

document.open();

④向文檔中添加內(nèi)容。

document.add(new Paragraph("Hello World"));

⑤關(guān)閉文檔。

document.close();

通過上面的5個步驟,就能產(chǎn)生一個Helloworld.PDF的文件,文件內(nèi)容為"Hello World"。

建立com.lowagie.text.Document對象的實例

com.lowagie.text.Document對象的構(gòu)建函數(shù)有三個,分別是:

public Document();

public Document(Rectangle pageSize);

public Document(Rectangle pageSize,

int marginLeft,

int marginRight,

int marginTop,

int marginBottom);

構(gòu)建函數(shù)的參數(shù)pageSize是文檔頁面的大小,對于第一個構(gòu)建函數(shù),頁面的大小為A4,同Document(PageSize.A4)的效果一樣;對于第三個構(gòu)建函數(shù),參數(shù)marginLeft、marginRight、marginTop、marginBottom分別為左、右、上、下的頁邊距。

通過參數(shù)pageSize可以設(shè)定頁面大小、面背景色、以及頁面橫向/縱向等屬性。iText定義了A0-A10、AL、LETTER、HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA 和FLSE等紙張類型,也可以通過Rectangle pageSize = new Rectangle(144, 720);自定義紙張。通過Rectangle方法rotate()可以將頁面設(shè)置成橫向。

書寫器(Writer)對象

一旦文檔(document)對象建立好之后,需要建立一個或多個書寫器(Writer)對象與之關(guān)聯(lián)。通過書寫器(Writer)對象可以將具體文檔存盤成需要的格式,如com.lowagie.text.PDF.PDFWriter可以將文檔存成PDF文件,com.lowagie.text.html.HtmlWriter可以將文檔存成html文件。

設(shè)定文檔屬性

在文檔打開之前,可以設(shè)定文檔的標(biāo)題、主題、作者、關(guān)鍵字、裝訂方式、創(chuàng)建者、生產(chǎn)者、創(chuàng)建日期等屬性,調(diào)用的方法分別是:

public boolean addTitle(String title)

public boolean addSubject(String subject)

public boolean addKeywords(String keywords)

public boolean addAuthor(String author)

public boolean addCreator(String creator)

public boolean addProducer()

public boolean addCreationDate()

public boolean addHeader(String name, String content)

其中方法addHeader對于PDF文檔無效,addHeader僅對html文檔有效,用于添加文檔的頭信息。

當(dāng)新的頁面產(chǎn)生之前,可以設(shè)定頁面的大小、書簽、腳注(HeaderFooter)等信息,調(diào)用的方法是:

public boolean setPageSize(Rectangle pageSize)

public boolean add(Watermark watermark)

public void removeWatermark()

public void setHeader(HeaderFooter header)

public void resetHeader()

public void setFooter(HeaderFooter footer)

public void resetFooter()

public void resetPageCount()

public void setPageCount(int pageN)

如果要設(shè)定第一頁的頁面屬性,這些方法必須在文檔打開之前調(diào)用。

對于PDF文檔,iText還提供了文檔的顯示屬性,通過調(diào)用書寫器的setViewerPreferences方法可以控制文檔打開時Acrobat Reader的顯示屬性,如是否單頁顯示、是否全屏顯示、是否隱藏狀態(tài)條等屬性。

另外,iText也提供了對PDF文件的安全保護,通過書寫器(Writer)的setEncryption方法,可以設(shè)定文檔的用戶口令、只讀、可打印等屬性。

添加文檔內(nèi)容

所有向文檔添加的內(nèi)容都是以對象為單位的,如Phrase、Paragraph、Table、Graphic對象等。比較常用的是段落(Paragraph)對象,用于向文檔中添加一段文字。

四、文本處理

iText中用文本塊(Chunk)、短語(Phrase)和段落(paragraph)處理文本。

文本塊(Chunk)是處理文本的最小單位,有一串帶格式(包括字體、顏色、大?。┑淖址M成。如以下代碼就是產(chǎn)生一個字體為HELVETICA、大小為10、帶下劃線的字符串:

Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));

短語(Phrase)由一個或多個文本塊(Chunk)組成,短語(Phrase)也可以設(shè)定字體,但對于其中以設(shè)定過字體的文本塊(Chunk)無效。通過短語(Phrase)成員函數(shù)add可以將一個文本塊(Chunk)加到短語(Phrase)中,如:phrase6.add(chunk);

段落(paragraph)由一個或多個文本塊(Chunk)或短語(Phrase)組成,相當(dāng)于WORD文檔中的段落概念,同樣可以設(shè)定段落的字體大小、顏色等屬性。另外也可以設(shè)定段落的首行縮進、對齊方式(左對齊、右對齊、居中對齊)。通過函數(shù)setAlignment可以設(shè)定段落的對齊方式,setAlignment的參數(shù)1為居中對齊、2為右對齊、3為左對齊,默認(rèn)為左對齊。

五、表格處理

iText中處理表格的類為:com.lowagie.text.Table和com.lowagie.text.PDF.PDFPTable,對于比較簡單的表格處理可以用com.lowagie.text.Table,但是如果要處理復(fù)雜的表格,這就需要com.lowagie.text.PDF.PDFPTable進行處理。這里就類com.lowagie.text.Table進行說明。

類com.lowagie.text.Table的構(gòu)造函數(shù)有三個:

①Table (int columns)

②Table(int columns, int rows)

③Table(Properties attributes)

參數(shù)columns、rows、attributes分別為表格的列數(shù)、行數(shù)、表格屬性。創(chuàng)建表格時必須指定表格的列數(shù),而對于行數(shù)可以不用指定。

建立表格之后,可以設(shè)定表格的屬性,如:邊框?qū)挾取⑦吙蝾伾?、襯距(padding space 即單元格之間的間距)大小等屬性。下面通過一個簡單的例子說明如何使用表格,代碼如下:

1:Table table = new Table(3);

2:table.setBorderWidth(1);

3:table.setBorderColor(new Color(0, 0, 255));

4:table.setPadding(5);

5:table.setSpacing(5);

6:Cell cell = new Cell("header");

7:cell.setHeader(true);

8:cell.setColspan(3);

9:table.addCell(cell);

10:table.endHeaders();

11:cell = new Cell("example cell with colspan 1 and rowspan 2");

12:cell.setRowspan(2);

13:cell.setBorderColor(new Color(255, 0, 0));

14:table.addCell(cell);

15:table.addCell("1.1");

16:table.addCell("2.1");

17:table.addCell("1.2");

18:table.addCell("2.2");

19:table.addCell("cell test1");

20:cell = new Cell("big cell");

21:cell.setRowspan(2);

22:cell.setColspan(2);

23:table.addCell(cell);

24:table.addCell("cell test2");

運行結(jié)果如下:

header

example cell with colspan 1 and rowspan 2 1.1 2.1

1.2 2.2

cell test1 big cell

cell test2

代碼1-5行用于新建一個表格,如代碼所示,建立了一個列數(shù)為3的表格,并將邊框?qū)挾仍O(shè)為1,顏色為藍色,襯距為5。

代碼6-10行用于設(shè)定表格的表頭,第7行cell.setHeader(true);是將該單元格作為表頭信息顯示;第8行cell.setColspan(3);指定了該單元格占3列;為表格添加表頭信息時,要注意的是一旦表頭信息添加完了之后,必須調(diào)用endHeaders()方法,如第10行,否則當(dāng)表格跨頁后,表頭信息不會再顯示。

代碼11-14行是向表格中添加一個寬度占一列,長度占二行的單元格。

往表格中添加單元格(cell)時,按自左向右、從上而下的次序添加。如執(zhí)行完11行代碼后,表格的右下方出現(xiàn)2行2列的空白,這是再往表格添加單元格時,先填滿這個空白,然后再另起一行,15-24行代碼說明了這種添加順序。

六、圖像處理

iText中處理表格的類為com.lowagie.text.Image,目前iText支持的圖像格式有:GIF, Jpeg, PNG, wmf等格式,對于不同的圖像格式,iText用同樣的構(gòu)造函數(shù)自動識別圖像格式。通過下面的代碼分別獲得gif、jpg、png圖像的實例。

Image gif = Image.getInstance("vonnegut.gif");

Image jpeg = Image.getInstance("myKids.jpg");

Image png = Image.getInstance("hitchcock.png");

圖像的位置

圖像的位置主要是指圖像在文檔中的對齊方式、圖像和文本的位置關(guān)系。IText中通過函數(shù)public void setAlignment(int alignment)進行處理,參數(shù)alignment為Image.RIGHT、Image.MIDDLE、Image.LEFT分別指右對齊、居中、左對齊;當(dāng)參數(shù)alignment為Image.TEXTWRAP、Image.UNDERLYING分別指文字繞圖形顯示、圖形作為文字的背景顯示。這兩種參數(shù)可以結(jié)合以達到預(yù)期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)顯示的效果為圖像右對齊,文字圍繞圖像顯示。

圖像的尺寸和旋轉(zhuǎn)

如果圖像在文檔中不按原尺寸顯示,可以通過下面的函數(shù)進行設(shè)定:

public void scaleAbsolute(int newWidth, int newHeight)

public void scalePercent(int percent)

public void scalePercent(int percentX, int percentY)

函數(shù)public void scaleAbsolute(int newWidth, int newHeight)直接設(shè)定顯示尺寸;函數(shù)public void scalePercent(int percent)設(shè)定顯示比例,如scalePercent(50)表示顯示的大小為原尺寸的50%;而函數(shù)scalePercent(int percentX, int percentY)則圖像高寬的顯示比例。

如果圖像需要旋轉(zhuǎn)一定角度之后在文檔中顯示,可以通過函數(shù)public void setRotation(double r)設(shè)定,參數(shù)r為弧度,如果旋轉(zhuǎn)角度為30度,則參數(shù)r= Math.PI / 6。

七、中文處理

默認(rèn)的iText字體設(shè)置不支持中文字體,需要下載遠(yuǎn)東字體包iTextAsian.jar,否則不能往PDF文檔中輸出中文字體。通過下面的代碼就可以在文檔中使用中文了:

BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);

Paragraph pragraph=new Paragraph("你好", FontChinese);

八、后計

iText還有很多高級的功能,這里就不一一介紹了,具體開發(fā)時可參考發(fā)布的文檔??偟膩碚f,iText是一套java環(huán)境下不錯的制作PDF的組件。因為iText支持jsp/javabean下的開發(fā),這使得B/S應(yīng)用中的報表問題能得到很好的解決。由于iText畢竟不是專門為制作報表設(shè)計,所有報表中的內(nèi)容、格式都需要通過寫代碼實現(xiàn),相對于那些專業(yè)的支持可視化設(shè)計的報表軟件來說,編程的工作量就有一定程度的增加。

java解析word文檔有哪些方法

java讀取word文檔時,雖然網(wǎng)上介紹了很多插件poi、java2Word、jacob、itext等等,poi無法讀取格式(新的API估

計行好像還在處于研發(fā)階段,不太穩(wěn)定,做項目不太敢用);java2Word、jacob容易報錯找不到注冊,比較詭異,我曾經(jīng)在不同的機器上試過,操作

方法完全一致,有的機器不報錯,有的報錯,去他們論壇找高人解決也說不出原因,項目部署用它有點玄;itxt好像寫很方便但是我查了好久資料沒有見到過關(guān)

于讀的好辦法。經(jīng)過一番選擇還是折中點采用rtf最好,畢竟rtf是開源格式,不需要借助任何插件,只需基本IO操作外加編碼轉(zhuǎn)換即可。rtf格式文件表

面看來和doc沒啥區(qū)別,都可以用word打開,各種格式都可以設(shè)定。

----- 實現(xiàn)的功能:讀取rtf模板內(nèi)容(格式和文本內(nèi)容),替換變化部分,形成新的rtf文檔。

----- 實現(xiàn)思路:模板中固定部分手動輸入,變化的部分用$info$表示,只需替換$info$即可。

1、采用字節(jié)的形式讀取rtf模板內(nèi)容

2、將可變的內(nèi)容字符串轉(zhuǎn)為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 bs.length;i++) {

bit = (bs[i] 0x0f0)

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 = new

FileInputStream(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 bytes

counts

if(bytesRead == -1) {// end of InputStream

System.out.println("讀取模板文件結(jié)束");

break;

}

sourcecontent += new String(b, 0, bytesRead); // convert to string

using bytes

}

}catch(Exception e){

e.printStackTrace();

}

return sourcecontent ;

}

以上為核心代碼,剩余部分就是替換,從新組裝java中的String.replace(oldstr,newstr);方法可以實現(xiàn),在這就不貼了。源代碼部分詳見附件。

運行源代碼前提:

c盤創(chuàng)建YQ目錄,將附件中"模板.rtf"復(fù)制到Y(jié)Q目錄之下,運行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 bs.length; i++) {

bit = (bs[i] 0x0f0)

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,int

flag){

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 new

String(c);

}

public void rgModel(String username, String content) {

// TODO Auto-generated method stub

Date current=new Date();

SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd

HH: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 bytes

counts

if(bytesRead == -1) {// end of InputStream

System.out.println("讀取模板文件結(jié)束");

break;

}

sourcecontent += new String(b, 0, bytesRead); // convert to string

using bytes

}

}catch(Exception e){

e.printStackTrace();

}

String targetcontent = "";

String array[] = content.split("~");

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

if(i==0){

targetcontent = replaceRTF(sourcecontent, array[i], i);

}else{

targetcontent = replaceRTF(targetcontent, array[i], i);

}

}

try {

FileWriter fw = new FileWriter(getSavePath()+"\\" +

targetname,true);

PrintWriter out = new PrintWriter(fw);

if(targetcontent.equals("")||targetcontent==""){

out.println(sourcecontent);

}else{

out.println(targetcontent);

}

out.close();

fw.close();

System.out.println(getSavePath()+" 該目錄下生成文件" +

targetname + " 成功");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

OperatorRTF oRTF = new OperatorRTF();

String content =

"2008年10月12日9時-2008年10月12日6時~我們參照檢驗藥品的方法~我們參照檢驗藥品的方法~我們參照檢驗藥品的方法~我們參照檢驗藥品的方法";

oRTF.rgModel("cheney",content);

}

}

java字符串如何解析成能運行的java代碼?

java字符串如何解析成運行的java代碼

有些情況下,不得不動態(tài)運行Java代碼,以便提供更加靈活的方式,以下代碼可參考(在JDK 1.5+平臺上運行通過):

public static void main(String[] args) {

int i = 10;

String code = "System.out.println(\"Hello World!\"+(13+2*5/3));";

code += "for(int i=0;i" + i + ";i++){";

code += " System.out.println(Math.pow(i,2));";

code += "}";

try {

run(code);

} catch (Exception e) {

e.printStackTrace();

}

}

private synchronized static File compile(String code) throws Exception {

File file = File.createTempFile("JavaRuntime", ".java", new File(System.getProperty("user.dir")));

file.deleteOnExit();

// 獲得類名

String classname = getBaseFileName(file);

// 將代碼輸出到文件

PrintWriter out = new PrintWriter(new FileOutputStream(file));

out.println(getClassCode(code, classname));

out.close();

// 編譯生成的java文件

String[] cpargs = new String[] { "-d",

System.getProperty("user.dir") + "\\WebRoot\\WEB-INF\\classes",

file.getName() };

int status = Main.compile(cpargs);

if (status != 0) {

throw new Exception("語法錯誤!");

}

return file;

}

private static synchronized void run(String code) throws Exception {

String classname = getBaseFileName(compile(code));

new File(System.getProperty("user.dir")

+ "\\WebRoot\\WEB-INF\\classes\\" + classname + ".class")

.deleteOnExit();

try {

Class cls = Class.forName(classname);

Method main = cls.getMethod("method", null);

main.invoke(cls, null);

} catch (Exception se) {

se.printStackTrace();

}

}

private static String getClassCode(String code, String className) {

StringBuffer text = new StringBuffer();

text.append("public class " + className + "{\n");

text.append(" public static void method(){\n");

text.append(" " + code + "\n");

text.append(" }\n");

text.append("}");

return text.toString();

}

private static String getBaseFileName(File file) {

String fileName = file.getName();

int index = fileName.indexOf(".");

String result = "";

if (index != -1) {

result = fileName.substring(0, index);

} else {

result = fileName;

}

return result;

}

java源文件解析

建一個Student實體類封裝數(shù)據(jù)

public static ListStudent readXml() {

ListStudent list = new ArrayListStudent();

//定義一個a href=";tn=44039180_cprfenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3uhnvryDYrjIBPyDYn1Rv0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1RznjcYn1TLnH04rjcYnjTvPf" target="_blank" class="baidu-highlight"dom解析/a器工廠實例

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try {

//由工廠實例得到一個a href=";tn=44039180_cprfenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3uhnvryDYrjIBPyDYn1Rv0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1RznjcYn1TLnH04rjcYnjTvPf" target="_blank" class="baidu-highlight"dom解析/a器

DocumentBuilder dom = factory.newDocumentBuilder();

//找到a href=";tn=44039180_cprfenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3uhnvryDYrjIBPyDYn1Rv0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1RznjcYn1TLnH04rjcYnjTvPf" target="_blank" class="baidu-highlight"xml文檔/a

File file=new File("src/com/jereh/ch05/Students.xml");

Document doc=dom.parse(file);

//

Element root = doc.getDocumentElement();

NodeList stuNodeList = root.getChildNodes();

for (int i = 0; i stuNodeList.getLength(); i++) {

Node stu = stuNodeList.item(i);

Student student = new Student();

if (stu != null stu.getNodeType() == Node.ELEMENT_NODE) {

// System.out.println(stu);

Element stuElement = (Element) stu;

student.setNo(stuElement.getAttribute("id"));

// stu.getAttributes().getNamedItem(null);

// Element stu=(Element)stuNodeList

NodeList info = stuElement.getChildNodes();

for (int j = 0; j info.getLength(); j++) {

info.item(j).getNodeName();

Node n = info.item(j);

if ("name".equals(n.getNodeName())) {

// n.getFirstChild().getNodeValue();

student.setName(n.getLastChild().getNodeValue());

} else if ("age".equals(n.getNodeName())) {

student.setAge(Integer.parseInt(n.getFirstChild()

.getNodeValue()));

}

list.add(student);

}

}

}

} catch (ParserConfigurationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SAXException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

// System.out.println(root.getNodeValue());

return list;

}

java解析lrc文件代碼

lrc可以通過如下util工具類進行轉(zhuǎn)換,如果想知道結(jié)果是否讀取的有問題,可以直接用記事本打開lrc文件的,之后和輸出結(jié)果比對一下就行。

package com.routon.utils;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import android.util.Log;

/**

* parse lrc file tool

* eg:

* utilLrc lrc = new utilLrc("/sdcard/test.lrc");

* get song name : String title = lrc.getTitle();

* get performer name : String artist = lrc.getArtist();

* get album name: String album = lrc.getAlbum();

* get lrcmaker name: String lrcMaker = lrc.getLrcMaker();

* get song list: ListStatement list = lrc.getLrcList();

*

* @author xuweilin

*

*/

public class utilLrc {

private static String TAG = "utilLrc";

public class Statement {

private double time = 0.0; //time, 0.01s

private String lyric = ""; //song word

/*

* get time

*/

public double getTime() {

return time;

}

/*

* set time

*/

public void setTime(double time) {

this.time = time;

}

/*

* set time.format:mm:ss.ms

*/

public void setTime(String time) {

String str[] = time.split(":|\\.");

this.time = Integer.parseInt(str[0])*60+Integer.parseInt(str[1])+Integer.parseInt(str[2])*0.01;

}

/*

* get lrc word

*/

public String getLyric() {

return lyric;

}

/*

* set lrc word

*/

public void setLyric(String lyric) {

this.lyric = lyric;

}

}

private BufferedReader bufferReader = null;

private String title = "";

private String artist = "";

private String album = "";

private String lrcMaker = "";

private ListStatement statements = new ArrayListStatement();

/*

*

* fileName

*/

public utilLrc(String fileName) throws IOException{

FileInputStream file = new FileInputStream(fileName);

bufferReader = new BufferedReader(new InputStreamReader(file, "utf-8"));

readData();

}

/*

* read the file

*/

private void readData() throws IOException{

statements.clear();

String strLine;

while(null != (strLine = bufferReader.readLine()))

{

if("".equals(strLine.trim()))

{

continue;

}

if(null == title || "".equals(title.trim()))

{

Pattern pattern = Pattern.compile("\\[ti:(.+?)\\]");

Matcher matcher = pattern.matcher(strLine);

if(matcher.find())

{

title=matcher.group(1);

continue;

}

}

if(null == artist || "".equals(artist.trim()))

{

Pattern pattern = Pattern.compile("\\[ar:(.+?)\\]");

Matcher matcher = pattern.matcher(strLine);

if(matcher.find())

{

artist=matcher.group(1);

continue;

}

}

if(null == album || "".equals(album.trim()))

{

Pattern pattern = Pattern.compile("\\[al:(.+?)\\]");

Matcher matcher = pattern.matcher(strLine);

if(matcher.find())

{

album=matcher.group(1);

continue;

}

}

if(null == lrcMaker || "".equals(lrcMaker.trim()))

{

Pattern pattern = Pattern.compile("\\[by:(.+?)\\]");

Matcher matcher = pattern.matcher(strLine);

if(matcher.find())

{

lrcMaker=matcher.group(1);

continue;

}

}

int timeNum=0;

String str[] = strLine.split("\\]");

for(int i=0; istr.length; ++i)

{

String str2[] = str[i].split("\\[");

str[i] = str2[str2.length-1];

if(isTime(str[i])){

++timeNum;

}

}

for(int i=0; itimeNum;++i)

{

Statement sm = new Statement();

sm.setTime(str[i]);

if(timeNumstr.length)

{

sm.setLyric(str[str.length-1]);

}

statements.add(sm);

}

}

sortLyric();

}

/*

* judge the string is or not date format.

*/

private boolean isTime(String string)

{

String str[] = string.split(":|\\.");

if(3!=str.length)

{

return false;

}

try{

for(int i=0;istr.length;++i)

{

Integer.parseInt(str[i]);

}

}

catch(NumberFormatException e)

{

Log.e(TAG, "isTime exception:"+e.getMessage());

return false;

}

return true;

}

/*

* sort the word by time.

*/

private void sortLyric()

{

for(int i=0;istatements.size()-1;++i)

{

int index=i;

double delta=Double.MAX_VALUE;

boolean moveFlag = false;

for(int j=i+1;jstatements.size();++j)

{

double sub;

if(0=(sub=statements.get(i).getTime()-statements.get(j).getTime()))

{

continue;

}

moveFlag=true;

if(subdelta)

{

delta=sub;

index=j+1;

}

}

if(moveFlag)

{

statements.add(index, statements.get(i));

statements.remove(i);

--i;

}

}

}

/**

* get title

* @return

*/

public String getTitle(){

return title;

}

/**

* get artist

* @return

*/

public String getArtist(){

return artist;

}

/**

* get album

* @return

*/

public String getAlbum(){

return album;

}

/**

* get lrc maker

* @return

*/

public String getLrcMaker(){

return lrcMaker;

}

/**

* get song list

* @return

*/

public ListStatement getLrcList(){

return statements;

}

}

文章題目:文檔解析java代碼,java源代碼解析
URL標(biāo)題:http://muchs.cn/article26/hssojg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計、營銷型網(wǎng)站建設(shè)域名注冊、全網(wǎng)營銷推廣、、動態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

營銷型網(wǎng)站建設(shè)