자바를 사용하여 텍스트 내용을 웹 페이지로 변환하는 실현 방법 공유

4437 단어 Java파일
먼저 간단한 파일 읽기와 쓰기를 바탕으로 File Helper 클래스의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
"; } 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"); } }
그리고 File Helper 클래스를 바탕으로 웹 페이지 메이커 클래스를 작성합니다. 그create Page 방법은 특정 파일의 내용을 특정한 웹 페이지에 생성하는 데 사용됩니다.
여기서 코드를 삽입하려면 코드를 삽입할 수 있습니다.

import java.util.StringTokenizer;


public class WebpageMaker {
  public static String initBegin() {
    String s = "<!doctype html><html><head><title></title></head><body>\r
"; return s; } public static String initEnd() { String s = "\r
</body></html>\r
"; return s; } public static void createPage(String inputfilename, String outputfilename) throws Exception { String content = FileHelper.readFile(inputfilename); StringTokenizer st = new StringTokenizer(content, "\r
"); 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
"; else ans += "\r
"; } 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!
"); 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!
"); return 0; }</pre><br /> </body></html>
효과는 다음과 같습니다.

hello world!
 :)
#include <stdio.h>
int main() {
  printf("hello world!
"); return 0; }

좋은 웹페이지 즐겨찾기