使用Java把文本内容转换成网页的实现方法分享
程序员文章站
2024-03-06 23:06:32
先以简单的文件读写实现为基础,filehelper类中的readfile方法用于读取文件内容,writefile方法用于向文件中写入内容。
import ja...
先以简单的文件读写实现为基础,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 style="background-color:aliceblue">#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; }