應用Java把文本內容轉換成網頁的完成辦法分享。本站提示廣大學習愛好者:(應用Java把文本內容轉換成網頁的完成辦法分享)文章只能為提供參考,不一定能成為您想要的結果。以下是應用Java把文本內容轉換成網頁的完成辦法分享正文
先以簡略的文件讀寫完成為基本,FileHelper類中的readFile辦法用於讀取文件內容,writeFile辦法用於向文件中寫入內容。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class FileHelper { public static String readFile(String filename) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(filename)); String ans = "", line = null; while((line = reader.readLine()) != null){ ans += line + "\r\n"; } reader.close(); return ans; } public static void writeFile(String content, String filename) throws Exception { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write(content); writer.flush(); writer.close(); } public static void main(String[] args) throws Exception { String ans = readFile("D:\\input.txt"); writeFile(ans, "D:\\output.txt"); } }
然後在FileHelper類的基本上寫一個WebpageMaker類,其createPage辦法用於將特定文件中的內容生成在特定的網頁中。
個中假如要拔出代碼可以將代碼參加中。
import java.util.StringTokenizer; public class WebpageMaker { public static String initBegin() { String s = "<!doctype html><html><head><title></title></head><body>\r\n"; return s; } public static String initEnd() { String s = "\r\n</body></html>\r\n"; return s; } public static void createPage(String inputfilename, String outputfilename) throws Exception { String content = FileHelper.readFile(inputfilename); StringTokenizer st = new StringTokenizer(content, "\r\n"); String ans = ""; ans += initBegin(); boolean isCoding = false; while(st.hasMoreElements()) { String s = st.nextToken(); int len = s.length(); for(int i=0;i<len;i++) { if(i+6 <= len && s.substring(i,i+6).equals("<alex>")) { isCoding = true; ans += "<pre style=\"background-color:aliceblue\">"; i += 5; continue; } if(i+7 <= len && s.substring(i,i+7).equals("</alex>")) { isCoding = false; ans += "</pre>"; i += 6; continue; } char c = s.charAt(i); if(c == '\"') ans += """; else if(c == '&') ans += "&"; else if(c == '<') ans += "<"; else if(c == '>') ans += ">"; else if(c == ' ') ans += " "; else if(c == '\t') ans += " "; else ans += c; } if(false == isCoding) ans += "<br />\r\n"; else ans += "\r\n"; } ans += initEnd(); FileHelper.writeFile(ans, outputfilename); } public static void main(String[] args) throws Exception { createPage("D://test.txt", "D://test.html"); } }
樣例:
輸出文件:test.txt
hello world! 年夜家好:) #include int main() { printf("hello world!\n"); return 0; }
輸入文件:test.html
<!doctype html><html><head><title></title></head><body> hello world!<br /> 年夜家好:)<br /> <pre >#include <stdio.h> int main() { printf("hello world!\n"); return 0; }</pre><br /> </body></html>
後果以下:
hello world! 年夜家好:) #include <stdio.h> int main() { printf("hello world!\n"); return 0; }