march alex's blog
hello,I am march alex
posts - 52,comments - 7,trackbacks - 0
之前写了一个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 += "&quot;";
                else if(c == '&') ans += "&amp;";
                else if(c == '<') ans += "&lt;";
                else if(c == '>') ans += "&gt;";
                else if(c == ' ') ans += "&nbsp;";
                else if(c == '\t') ans += "&nbsp;&nbsp;&nbsp;&nbsp;";
                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;
}
posted on 2015-03-06 16:36 marchalex 阅读(354) 评论(2)  编辑  收藏 所属分类: java小程序

FeedBack:
# re: Java根据文本内容生成网页
2015-03-06 23:52 | gaochang
servlet?  回复  更多评论
  
# re: Java根据文本内容生成网页
2015-03-07 00:10 | marchalex
@gaochang
暂时还不会servlet,以后有时间可能会研究吧:)  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: