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 = "

\r\n";

return s;

}

public static String initEnd() {

String s = "\r\n\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

if(i+6 <= len && s.substring(i,i+6).equals("")) {

isCoding = true;

ans += "

";

i += 5;

continue;

}

if(i+7 <= len && s.substring(i,i+7).equals("")) {

isCoding = false;

ans += "";

i += 6;

continue;

}

char c = s.charAt(i);

if(c == '\"') ans += """;

else if(c == '&') ans += "&";

else if(c == '

else if(c == '>') ans += ">";

else if(c == ' ') ans += " ";

else if(c == '\t') ans += "    ";

else ans += c;

}

if(false == isCoding)

ans += "
\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

hello world!

大家好:)

#include 

int main() {

printf("hello world!\n");

return 0;

}

效果如下:

hello world!

大家好:)

#include

int main() {

printf("hello world!\n");

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值