java程序怎么读取html网页?

html-css010

java程序怎么读取html网页?,第1张

步骤:

一、使用java.net包下的URL类,可以将一个网页(链接)封装成一个URL对象。

二、URL对象有一个openStream()方法,使用该方法可以获取该网页的输入流,我们可以通过读取输入流的方式获得网页的内容,并通过输出流写入HTML文件中。

补充:

步骤:

1.通过URL对象的openStream()方法获得网页的字节输入流 。

2.为字节输入流加缓冲 。

3. 创建字节输出流对象 。

4. 为字节输出流加缓冲 。

5. 读取数据,并写入HTML文件 。

可以通过使用Spire.Doc for Java进行转换。

首先需要安装Spire.Doc for Java。可在 Java 程序中添加 Spire.Doc for Java 文件作为依赖项。JAR 文件可以从此链接下载。 如果您使用 Maven,则可以将以下代码添加到项目的 pom.xml 文件中,从而轻松地在应用程序中导入 JAR 文件。

<repositories>

<repository>

<id>com.e-iceblue</id>

<name>e-iceblue</name>

<url>https://repo.e-iceblue.cn/repository/maven-public/</url>

</repository></repositories><dependencies>

<dependency>

<groupId>e-iceblue</groupId>

<artifactId>spire.doc</artifactId>

<version>5.2.3</version>

</dependency></dependencies>

具体分为以下两种情况:

HTML String另存为PDF格式

Java代码如下:

import com.spire.doc.*import java.io.*public class htmlStringToWord {

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

String inputHtml = "InputHtml.txt"

//新建Document对象

Document document = new Document()

//添加section

Section sec = document.addSection()

String htmlText = readTextFromFile(inputHtml)

//添加段落并写入HTML文本

sec.addParagraph().appendHTML(htmlText)

//文档另存为PDF

document.saveToFile("HTMLstringToPDF.pdf", FileFormat.PDF)

}

public static String readTextFromFile(String fileName) throws IOException{

StringBuffer sb = new StringBuffer()

BufferedReader br = new BufferedReader(new FileReader(fileName))

String content = null

while ((content = br.readLine()) != null) {

sb.append(content)

}

return sb.toString()

}

}

2.HTML file另存为PDF格式

import com.spire.doc.*import com.spire.doc.documents.XHTMLValidationTypepublic class htmlFileToWord {

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

//加载HTML文档

Document document = new Document()

document.loadFromFile("InputHtmlFile.html", FileFormat.Html, XHTMLValidationType.None)

//文档另存为PDF

document.saveToFile("Result.pdf",FileFormat.PDF)

}

}

希望对您有帮助。

     java读取html文件跟读取普通文件一样,都是使用输入输出流,但是java读取html文件之后还需要解析,使用Jsoup对html进行解析。下面是一个java读取带表格的任意html文件,并把html文件转换成excel的例子。

  要求: 要求能够实现给出任意带table表格的html文件,生成与表格相同内容的excel文件,附件可以作为测试文件,提供给定的roster.html文件,通过java代码,实现生成与html页面的table相同样式的roster.xls文件。

首先看roster.html:

java代码:

import java.io.BufferedReader

import java.io.File

import java.io.FileReader

import java.io.IOException

import jxl.Workbook

import jxl.write.Label

import jxl.write.WritableCellFormat

import jxl.write.WritableFont

import jxl.write.WritableSheet

import jxl.write.WritableWorkbook

import jxl.write.WriteException

import jxl.write.biff.RowsExceededException

import org.jsoup.Jsoup

import org.jsoup.nodes.Document

import org.jsoup.nodes.Element

import org.jsoup.select.Elements

public class HTMLTOExcel {

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

///读取classpath目录下面的路径

String path=HTMLTOExcel.class.getResource("/").getPath()

path+="roster.html"

toExcel(path,"roster")      

    }

    //得到Document并且设置编码格式

public static Document getDoc(String fileName) throws IOException{

      File myFile=new File(fileName)

      Document doc= Jsoup.parse(myFile, "GBK","")

      return doc

}

///这个方法用于根据trs行数和sheet画出整个表格

public static void mergeColRow(Elements trs,WritableSheet sheet) throws RowsExceededException, WriteException{

int[][] rowhb=new int[300][50]

for(int i=0i<trs.size()i++){

 Element tr=trs.get(i)

 Elements tds=tr.getElementsByTag("td")

 

 int realColNum=0

 for(int j=0j<tds.size()j++){

  Element td=tds.get(j)  

  if(rowhb[i][realColNum]!=0){

  realColNum=getRealColNum(rowhb,i,realColNum)

  }

  int rowspan=1

  int colspan=1

  if(td.attr("rowspan")!=""){

  rowspan = Integer.parseInt(td.attr("rowspan"))

  }

  if(td.attr("colspan")!=""){

  colspan = Integer.parseInt(td.attr("colspan"))

  }

  String text=td.text()

  drawMegerCell(rowspan,colspan,sheet,realColNum,i,text,rowhb)

  realColNum=realColNum+colspan

 }

 

}

}

///这个方法用于根据样式画出单元格,并且根据rowpan和colspan合并单元格

public static void drawMegerCell(int rowspan,int colspan,WritableSheet sheet,int realColNum,int realRowNum,String text,int[][] rowhb) throws RowsExceededException, WriteException{

  for(int i=0i<rowspani++){

  for(int j=0j<colspanj++){

  if(i!=0||j!=0){

 text=""

  }

  Label label = new Label(realColNum+j,realRowNum+i,text)

   WritableFont countents = new WritableFont(WritableFont.TIMES,10) // 设置单元格内容,字号12  

   WritableCellFormat cellf = new WritableCellFormat(countents ) 

   cellf.setAlignment(jxl.format.Alignment.CENTRE)//把水平对齐方式指定为居中

   cellf.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE)//把垂直对齐方式指定为居

   label.setCellFormat(cellf)

   sheet.addCell(label)

   rowhb[realRowNum+i][realColNum+j]=1

  }

  }

  sheet.mergeCells(realColNum,realRowNum, realColNum+colspan-1,realRowNum+rowspan-1)

}

public static int getRealColNum(int[][] rowhb,int i,int realColNum){

while(rowhb[i][realColNum]!=0){

realColNum++

}

return realColNum

}

///根据colgroups设置表格的列宽

public static void setColWidth(Elements colgroups,WritableSheet sheet){

 if(colgroups.size()>0){

 Element colgroup=colgroups.get(0)

 Elements cols=colgroup.getElementsByTag("col")

 for(int i=0i<cols.size()i++){

 Element col=cols.get(i)

 String strwd=col.attr("width")

 if(col.attr("width")!=""){

 int wd=Integer.parseInt(strwd)

 sheet.setColumnView(i,wd/8)

 }

 

 }

 

 }

}

//toExcel是根据html文件地址生成对应的xls

public static void toExcel(String fileName,String excelName)throws IOException{

Document doc=getDoc(fileName)

    String title = doc.title()

    ///得到样式,以后可以根据正则表达式解析css,暂且没有找到cssparse

    Elements style= doc.getElementsByTag("style")

    ///得到Table,demo只演示输入一个table,以后可以用循环遍历tables集合输入所有table

    Elements tables= doc.getElementsByTag("TABLE")    

    if(tables.size()==0){

    return

    }

    Element table=tables.get(0)

   //得到所有行

    Elements trs = table.getElementsByTag("tr")

    ///得到列宽集合

    Elements colgroups=table.getElementsByTag("colgroup")

    

   try {

   //文件保存到classpath目录下面

    String path=HTMLTOExcel.class.getResource("/").getPath()

path+=excelName+".xls"

 System.out.println(path)

    WritableWorkbook book = Workbook.createWorkbook(new File(path))    

    WritableSheet sheet = book.createSheet("人事关系", 0)  

    setColWidth(colgroups,sheet)

    mergeColRow(trs,sheet)    

    book.write()    

    book.close()    

   } catch (RowsExceededException e) {

        e.printStackTrace()

   } catch (WriteException e) { 

        e.printStackTrace()

   }

}

}

解析html文件的例子文档地址:http://blog.csdn.net/androidwuyou/article/details/52636821