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; } } }
ubuntu下用java代码调用命令将java格式文件转换为html格式文件,布布扣,bubuko.com
ubuntu下用java代码调用命令将java格式文件转换为html格式文件
原文:http://blog.csdn.net/liu_chunhui/article/details/38141899