首先我们应该在电脑上装上GNU Source-highlight 3.1.7,给个链接参考:
生成html文件如下
http://www.gnu.org/software/src-highlite/#mozTocId120994
下面代码实现了 将java类型的代码转换为html文件类型的代码,如果java代码的文件名为 helloword.java,则转换为html格式的文件名为helloword.java.html,将java代码在浏览器上显示出来。其次我还将html文件中的内容提取出来,便于在html文件里编写便于网页展示java代码。
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.*;
public class ChangeFileType {
public static void main(String[] args) {
change ch = new change();
String filename = "ChangeFileType.java";
File file = new File(filename);
if (!file.exists()) {
System.err.println("create file fail!");
}
// File tempFile;
// tempFile = ch.changeFile( file ); // 得到HTML文件
String result = ch.changeFile(file); // 得到HTML文件返回的字符串
System.out.println(result);
}
}
class change {
public String changeFile(File beginFile) {
String fileName = beginFile.getName();
String cmd = "source-highlight ChangeFileType.java";
Runtime run = Runtime.getRuntime(); // 返回与当前 Java 应用程序相关的运行时对象
try {
Process pro = run.exec(cmd); // 启动另一个进程来执行命令
BufferedInputStream in = new BufferedInputStream(
pro.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
String lineStr;
while ((lineStr = inBr.readLine()) != null)
// 获得命令执行后在控制台的输出信息
System.out.println(lineStr);// 打印输出信息
// 检查命令是否执行失败。
if (pro.waitFor() != 0) {
if (pro.exitValue() == 1)// pro.exitValue()==0表示正常结束,1:非正常结束
System.err.println("Executive Command Fail!");
}
inBr.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
fileName = fileName + ".html";
File endFile = new File(fileName);
String result = changeToString(endFile);
return result; // 返回转换后的的字符串
// return endFile; // 返回转换后的HTML文件
}
public String changeToString(File file) {
InputStreamReader reader = null;
StringWriter writer = new StringWriter();
try {
reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
// 将输入流写入输出流
char[] buffer = new char[1024];
int n = 0;
while (-1 != (n = reader.read(buffer))) {
writer.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 返回转换结果
if (writer != null) {
return writer.toString();
} else {
return null;
}
}
}
生成html文件如下
页面展示:
注:
如出现
java.io.UnsupportedEncodingException:错误;
at sun.nio.cs.StreamDecoder.forInputStreamReader(StreamDecoder.java:71)
at java.io.InputStreamReader.<init>(InputStreamReader.java:100)
at change.changeToString(ChangeFileType.java:67)
at change.changeFile(ChangeFileType.java:54)
at ChangeFileType.main(ChangeFileType.java:21)
at java.io.InputStreamReader.<init>(InputStreamReader.java:100)
at change.changeToString(ChangeFileType.java:67)
at change.changeFile(ChangeFileType.java:54)
at ChangeFileType.main(ChangeFileType.java:21)
是支持的编码问题
解决: reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
找到合适的编码