使用Java把文本内容转换成网页的实现方法分享
先以简单的文件读写实现为基础,FileHelper类中的readFile方法用于读取文件内容,writeFile方法用于向文件中写入内容。
importjava.io.BufferedReader; importjava.io.BufferedWriter; importjava.io.FileReader; importjava.io.FileWriter; publicclassFileHelper{ publicstaticStringreadFile(Stringfilename)throwsException{ BufferedReaderreader=newBufferedReader(newFileReader(filename)); Stringans="",line=null; while((line=reader.readLine())!=null){ ans+=line+"\r\n"; } reader.close(); returnans; } publicstaticvoidwriteFile(Stringcontent,Stringfilename)throwsException{ BufferedWriterwriter=newBufferedWriter(newFileWriter(filename)); writer.write(content); writer.flush(); writer.close(); } publicstaticvoidmain(String[]args)throwsException{ Stringans=readFile("D:\\input.txt"); writeFile(ans,"D:\\output.txt"); } }
然后在FileHelper类的基础上写一个WebpageMaker类,其createPage方法用于将特定文件中的内容生成在特定的网页中。
其中如果要插入代码可以将代码加入中。
importjava.util.StringTokenizer; publicclassWebpageMaker{ publicstaticStringinitBegin(){ Strings="<!doctypehtml><html><head><title></title></head><body>\r\n"; returns; } publicstaticStringinitEnd(){ Strings="\r\n</body></html>\r\n"; returns; } publicstaticvoidcreatePage(Stringinputfilename,Stringoutputfilename)throwsException{ Stringcontent=FileHelper.readFile(inputfilename); StringTokenizerst=newStringTokenizer(content,"\r\n"); Stringans=""; ans+=initBegin(); booleanisCoding=false; while(st.hasMoreElements()){ Strings=st.nextToken(); intlen=s.length(); for(inti=0;i<len;i++){ if(i+6<=len&&s.substring(i,i+6).equals("<alex>")){ isCoding=true; ans+="<prestyle=\"background-color:aliceblue\">"; i+=5; continue; } if(i+7<=len&&s.substring(i,i+7).equals("</alex>")){ isCoding=false; ans+="</pre>"; i+=6; continue; } charc=s.charAt(i); if(c=='\"')ans+="""; elseif(c=='&')ans+="&"; elseif(c=='<')ans+="<"; elseif(c=='>')ans+=">"; elseif(c=='')ans+=" "; elseif(c=='\t')ans+=" "; elseans+=c; } if(false==isCoding) ans+="<br/>\r\n"; else ans+="\r\n"; } ans+=initEnd(); FileHelper.writeFile(ans,outputfilename); } publicstaticvoidmain(String[]args)throwsException{ createPage("D://test.txt","D://test.html"); } }
样例:
输入文件:test.txt
helloworld! 大家好:) #include intmain(){ printf("helloworld!\n"); return0; }
输出文件:test.html
<!doctypehtml><html><head><title></title></head><body> helloworld!<br/> 大家好:)<br/> <prestyle="background-color:aliceblue">#include<stdio.h> intmain(){ printf("helloworld!\n"); return0; }</pre><br/> </body></html>
效果如下:
helloworld! 大家好:) #include<stdio.h> intmain(){ printf("helloworld!\n"); return0; }