將純文本文件(含代碼片段)自動轉換為可瀏覽的 HTML 網頁,需求包括:保留換行、空格轉義、代碼塊高亮顯示、特殊字符安全轉義。
import java.io.*;
public class FileHelper {
public static String readFile(String filename) throws Exception {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\r\n");
}
}
return content.toString();
}
public static void writeFile(String content, String filename) throws Exception {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(content);
}
}
}
import java.util.StringTokenizer;
public class WebpageMaker {
private static final String HTML_BEGIN = " \r\n";
private static final String HTML_END = "\r\n\r\n";
public static void createPage(String inputFile, String outputFile) throws Exception {
String content = FileHelper.readFile(inputFile);
StringTokenizer st = new StringTokenizer(content, "\r\n");
StringBuilder html = new StringBuilder(HTML_BEGIN);
boolean inCodeBlock = false;
while (st.hasMoreTokens()) {
String line = st.nextToken();
int len = line.length();
for (int i = 0; i < len; i++) {
// 檢測代碼塊標記 ...
if (i + 6 <= len && line.substring(i, i + 6).equals("")) {
inCodeBlock = true;
html.append("");
i += 5;
continue;
}
if (i + 7 <= len && line.substring(i, i + 7).equals(" ")) {
inCodeBlock = false;
html.append("");
i += 6;
continue;
}
char c = line.charAt(i);
// 特殊字符轉義
switch (c) {
case '"': html.append("""); break;
case '&': html.append("&"); break;
case '<': html.append("<"); break;
case '>': html.append(">"); break;
case ' ': html.append(" "); break;
case '\t': html.append(" "); break;
default: html.append(c);
}
}
if (!inCodeBlock) {
html.append("hello world! 大家好:) #includeint main() { printf("hello world!\n"); return 0; }
hello world!
大家好:)
#include <stdio.h>
int main() {
printf("hello world!\n");
return 0;
}
hello world! 大家好:)
#include <stdio.h>
int main() {
printf("hello world!\n");
return 0;
}
flexmark-java)這個簡單生成器展示了 Java 處理文本、生成 HTML 的核心思路,可作為文檔自動化工具的起點。