java中将java文件转换为html一个文件,先使用file类读取java文件,然后使用string进行分割、替换等 *** 作,输出html后缀名的文件,如下代码:
import java.io.BufferedReaderimport java.io.BufferedWriter
import java.io.File
import java.io.FileInputStream
import java.io.FileWriter
import java.io.IOException
import java.io.InputStreamReader
public class Change {
String textHtml = ""
String color = "#00688B"
//读取文件
public void ReadFile(String filePath) {
BufferedReader bu = null
InputStreamReader in = null
try {
File file = new File(filePath)
if (file.isFile() && file.exists()) {
in = new InputStreamReader(new FileInputStream(file))
bu = new BufferedReader(in)
String lineText = null
textHtml = "<html><body>"
while ((lineText = bu.readLine()) != null) {
lineText = changeToHtml(lineText)
lineText += "</br>"
textHtml += lineText
}
textHtml += "</html></body>"
} else {
System.out.println("文件不存在")
}
} catch (Exception e) {
e.printStackTrace()
} finally {
try {
bu.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
//输出文件
public void writerFile(String writepath) {
File file = new File(writepath)
BufferedWriter output = null
try {
output = new BufferedWriter(new FileWriter(file))
System.out.println(textHtml)
output.write(textHtml)
} catch (IOException e) {
e.printStackTrace()
} finally {
try {
output.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
//文件转换
public String changeToHtml(String text) {
text = text.replace("&", "&")
text = text.replace(" ", " ")
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace("\"", """)
text = text.replace(" ", " ")
text = text.replace("public", "<b><font color='"+color+"'>public</font></b>")
text = text.replace("class", "<b><font color='"+color+"'>class</font></b>")
text = text.replace("static", "<b><font color='"+color+"'>static</font></b>")
text = text.replace("void", "<b><font color='"+color+"'>void</font></b>")
String t = text.replace("//", "<font color=green>//")
if (!text.equals(t)) {
System.out.println("t:"+t)
text = t + "</font>"
}
return text
}
public static void main(String[] args) {
System.out.println("第一个参数为读取文件路径,第二个参数为生成文件路径")
if(args.length<1){
System.out.println("请<a href="https://www.baidu.com/s?wd=%E8%BE%93%E5%85%A5%E6%96%87%E4%BB%B6&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1Y3P16znjKBn1uWPvnzPWcY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6K1TL0qnfK1TL0z5HD0IgF_5y9YIZ0lQzqlpA-bmyt8mh7GuZR8mvqVQL7dugPYpyq8Q1DsPjTdnWTvPjT3n1T4n1ckn1b" target="_blank" class="baidu-highlight">输入文件</a>路径")
return
}else if(args.length<2){
System.out.println("请输入生成文件")
return
}
Change c = new Change()
c.ReadFile(args[0])
c.writerFile(args[1])
}
}
参考如下例子,就可以轻松将txt文件转化为html文件:private static String txtToHtml(String s) {
StringBuilder builder = new StringBuilder()
boolean previousWasASpace = false
for (char c : s.toCharArray()) {
if (c == ' ') {
if (previousWasASpace) {
builder.append(" ")
previousWasASpace = false
continue
}
previousWasASpace = true
} else {
previousWasASpace = false
}
switch (c) {
case '<':
builder.append("<")
break
case '>':
builder.append(">")
break
case '&':
builder.append("&")
break
case '"':
builder.append(""")
break
case '\n':
builder.append("<br>")
break
// We need Tab support here, because we print StackTraces as HTML
case '\t':
builder.append(" ")
break
default:
builder.append(c)
}
}
String converted = builder.toString()
String str = "(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{}:\'\".,<>?«»“”‘’]))"
Pattern patt = Pattern.compile(str)
Matcher matcher = patt.matcher(converted)
converted = matcher.replaceAll("<a href=\"$1\">$1</a>")
return converted
}
java将Word/Excel/PDF文件转换成HTML整理项目开发过程中,需求涉及到了各种文档转换为HTML或者网页易显示格式,现在将实现方式整理如下:
一、使用Jacob转换Word,Excel为HTML
“JACOB一个Java-COM中间件.通过这个组件你可以在Java应用程序中调用COM组件和Win32 libraries。”
首先下载Jacob包,JDK1.5以上需要使用Jacob1.9版本(JDK1.6尚未测试),与先前的Jacob1.7差别不大
1、将压缩包解压后,Jacob.jar添加到Libraries中;
2、将Jacob.dll放至“WINDOWS\SYSTEM32”下面。
需要注意的是:
【使用IDE启动Web服务器时,系统读取不到Jacob.dll,例如用MyEclipse启动Tomcat,就需要将dll文件copy到MyEclipse安装目录的“jre\bin”下面。
一般系统没有加载到Jacob.dll文件时,报错信息为:“java.lang.UnsatisfiedLinkError: no jacob in java.library.path”】
新建类:
1public class JacobUtil
2{
3public static final int WORD_HTML = 8
4
5public static final int WORD_TXT = 7
6
7public static final int EXCEL_HTML = 44
8
9/** *//**
10 * WORD转HTML
11 * @param docfile WORD文件全路径
12 * @param htmlfile 转换后HTML存放路径
13 */
14public static void wordToHtml(String docfile, String htmlfile)
15{
16ActiveXComponent app = new ActiveXComponent("Word.Application")// 启动word
17try
18{
19app.setProperty("Visible", new Variant(false))
20Dispatch docs = app.getProperty("Documents").toDispatch()
21Dispatch doc = Dispatch.invoke(
22docs,
23"Open",
24Dispatch.Method,
25new Object[] { docfile, new Variant(false),
26new Variant(true) }, new int[1]).toDispatch()
27Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
28htmlfile, new Variant(WORD_HTML) }, new int[1])
29Variant f = new Variant(false)
30Dispatch.call(doc, "Close", f)
31}
32catch (Exception e)
33{
34e.printStackTrace()
35}
36finally
37{
38app.invoke("Quit", new Variant[] {})
39}
40}
41
42/** *//**
43 * EXCEL转HTML
44 * @param xlsfile EXCEL文件全路径
45 * @param htmlfile 转换后HTML存放路径
46 */
47public static void excelToHtml(String xlsfile, String htmlfile)
48{
49ActiveXComponent app = new ActiveXComponent("Excel.Application")// 启动word
50try
51{
52app.setProperty("Visible", new Variant(false))
53Dispatch excels = app.getProperty("Workbooks").toDispatch()
54Dispatch excel = Dispatch.invoke(
55excels,
56"Open",
57Dispatch.Method,
58new Object[] { xlsfile, new Variant(false),
59new Variant(true) }, new int[1]).toDispatch()
60Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {
61htmlfile, new Variant(EXCEL_HTML) }, new int[1])
62Variant f = new Variant(false)
63Dispatch.call(excel, "Close", f)
64}
65catch (Exception e)
66{
67e.printStackTrace()
68}
69finally
70{
71app.invoke("Quit", new Variant[] {})
72}
73}
74
75}
76
当时我在找转换控件时,发现网易也转载了一偏关于Jacob使用帮助,但其中出现了比较严重的错误:String htmlfile = "C:\\AA"
只指定到了文件夹一级,正确写法是String htmlfile = "C:\\AA\\xxx.html"
到此WORD/EXCEL转换HTML就已经差不多了,相信大家应该很清楚了:)
二、使用XPDF将PDF转换为HTML
1、下载xpdf最新版本,地址:http://www.foolabs.com/xpdf/download.html
我下载的是xpdf-3.02pl2-win32.zip
2、下载中文支持包
我下载的是xpdf-chinese-simplified.tar.gz
3、下载pdftohtml支持包
地址:http://sourceforge.net/projects/pdftohtml/
我下载的是:pdftohtml-0.39-win32.tar.gz
4、解压调试
1) 先将xpdf-3.02pl2-win32.zip解压,解压后的内容可根据需要进行删减,如果只需要转换为txt格式,其他的exe文件可以删除,只保留pdftotext.exe,以此类推;
2) 然后将xpdf-chinese-simplified.tar.gz解压到刚才xpdf-3.02pl2-win32.zip的解压目录;
3) 将pdftohtml-0.39-win32.tar.gz解压,pdftohtml.exe解压到xpdf-3.02pl2-win32.zip的解压目录;
4) 目录结构:
+---[X:\xpdf]
|-------各种转换用到的exe文件
|
|-------xpdfrc
|
+------[X:\xpdf\xpdf-chinese-simplified]
|
|
+-------很多转换时需要用到的字符文件
xpdfrc:此文件是用来声明转换字符集对应路径的文件
5) 修改xpdfrc文件(文件原名为sample-xpdfrc)
修改文件内容为:
Txt代码
#----- begin Chinese Simplified support package
cidToUnicodeAdobe-GB1 xpdf-chinese-simplified\Adobe-GB1.cidToUnicode
unicodeMap ISO-2022-CN xpdf-chinese-simplified\ISO-2022-CN.unicodeMap
unicodeMap EUC-CN xpdf-chinese-simplified\EUC-CN.unicodeMap
unicodeMap GBKxpdf-chinese-simplified\GBK.unicodeMap
cMapDir Adobe-GB1 xpdf-chinese-simplified\CMap
toUnicodeDirxpdf-chinese-simplified\CMap
fontDir C:\WINDOWS\Fonts
displayCIDFontTT Adobe-GB1 C:\WINDOWS\Fonts\simhei.ttf
#----- end Chinese Simplified support package
6) 创建bat文件pdftohtml.bat(放置的路径不能包含空格)
内容为:
Txt代码
@echo off
set folderPath=%1
set filePath=%2
cd /d %folderPath%
pdftohtml -enc GBK %filePath%
exit
7) 创建类
JAVA代码
public class ConvertPdf
{
private static String INPUT_PATH
private static String PROJECT_PATH
public static void convertToHtml(String file, String project)
{
INPUT_PATH = file
PROJECT_PATH = project
if(checkContentType()==0)
{
toHtml()
}
}
private static int checkContentType()
{
String type = INPUT_PATH.substring(INPUT_PATH.lastIndexOf(".") + 1, INPUT_PATH.length())
.toLowerCase()
if (type.equals("pdf"))
return 0
else
return 9
}
private static void toHtml()
{
if(new File(INPUT_PATH).isFile())
{
try
{
String cmd = "cmd /c start X:\\pdftohtml.bat \"" + PROJECT_PATH + "\" \"" + INPUT_PATH + "\""
Runtime.getRuntime().exec(cmd)
}
catch (IOException e)
{
e.printStackTrace()
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)