You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Java代码转彩色HTML的指定显示格式配置?

Java to Colored HTML Converter: Fixes & Implementation Guide

Got it, let's get your Java-to-colored-HTML tool working exactly as you need. Below are the step-by-step adjustments to the java2colorHTML class, plus how to run it properly.

Key Fixes & Adjustments

1. Ensure < and > Display Correctly

Your existing code already handles this, but let's confirm the critical order: we must escape </> before adding any HTML tags (like <br> or &nbsp;). The current code does this right, but don't reorder these lines—if you add HTML first, you'll accidentally escape the tags themselves!

// Keep these lines at the top of the processing flow
txt = txt.replace("<", "&lt;");
txt = txt.replace(">", "&gt;");

2. Color String Literals Gray (and Protect Internal //)

The original code had two bugs here: it stripped the surrounding double quotes, and it let internal // get colored as comments later. Here's how to fix it:

  • Wrap the entire "..." (quotes included) in gray font tags
  • Replace internal // with a temporary placeholder before processing comments, then restore it at the end

Update the string literal processing loop to this:

int bgn = 0;
while (true) {
    bgn = txt.indexOf("\"", bgn == 0 ? 0 : bgn + 1);
    if (bgn == -1) break;
    int end = txt.indexOf("\"", bgn + 1);
    if (end == -1) break; // Handle unclosed quotes gracefully
    
    // Grab the full string including quotes
    String strLiterals = txt.substring(bgn, end + 1);
    // Remove any existing font tags to avoid nesting issues
    strLiterals = strLiterals.replaceAll("</*[^<>]+>", "");
    // Replace internal // with a placeholder to avoid comment coloring
    strLiterals = strLiterals.replace("//", "__SLASH_SLASH__");
    // Wrap the whole string in gray font
    strLiterals = "<font color=\"#a3a3a3\">" + strLiterals + "</font>";
    
    txt = txt.substring(0, bgn) + strLiterals + txt.substring(end + 1);
    bgn += strLiterals.length();
}

Then, add this line right before outputting the HTML to restore the // in strings:

txt = txt.replace("__SLASH_SLASH__", "//");

3. Add Multi-Line Comment (/* ... */) Coloring

The original code only handled single-line // comments. Add this loop to process multi-line comments (wrap them in green font) after processing strings (so we don't color comments inside strings):

// Process multi-line /* ... */ comments
bgn = 0;
while (true) {
    bgn = txt.indexOf("/*", bgn == 0 ? 0 : bgn + 1);
    if (bgn == -1) break;
    int end = txt.indexOf("*/", bgn + 2);
    if (end == -1) end = txt.length(); // Handle unclosed comments gracefully
    
    String multiComment = txt.substring(bgn, end + 2);
    multiComment = multiComment.replaceAll("</*[^<>]+>", "");
    multiComment = "<font color=\"#009900\">" + multiComment + "</font>";
    
    txt = txt.substring(0, bgn) + multiComment + txt.substring(end + 2);
    bgn += multiComment.length();
}

Full Modified Code

Here's the complete updated java2colorHTML class with all fixes:

import java.io.*;
class java2colorHTML {
    public static String [] modifiers = {"class", "public", "private", "static", "void", "int", "long", };
    public static String [] other_keywords = {"import", "throws", "new", "null", "true", "false", "for", "while", "do", "if", "else", "break", "return", "continue",};

    public static void main(String [] args) throws IOException {
        // Running: java java2colorHTML <input-file.java>
        // Replace myIO.readFile with this block if you don't have the myIO class
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(args[0]));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();
        String txt = sb.toString();
        
        // 1. Escape < and > first (critical order!)
        txt = txt.replace("<", "&lt;");
        txt = txt.replace(">", "&gt;");
        
        // Handle line breaks, spaces, tabs
        txt = txt.replaceAll("\r\n|\n", "<br>");
        txt = txt.replace(" ", "&nbsp;");
        txt = txt.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
        
        // Color modifiers
        for (String w : modifiers) {
            txt = txt.replaceAll(w + "&nbsp;", "<font color=\"#aa33ff\">" + w + "</font>&nbsp;");
        }
        
        // Color other keywords
        for (String w : other_keywords) {
            txt = txt.replaceAll(w + "&nbsp;", "<font color=\"#3333ff\">" + w + "</font>&nbsp;");
            txt = txt.replaceAll("&nbsp;" + w, "&nbsp;<font color=\"#3333ff\">" + w + "</font>");
            txt = txt.replaceAll("\\(" + w + "\\)", "(<font color=\"#3333ff\">" + w + "</font>)");
        }
        
        // 2. Process string literals (gray, protect internal //)
        int bgn = 0;
        while (true) {
            bgn = txt.indexOf("\"", bgn == 0 ? 0 : bgn + 1);
            if (bgn == -1) break;
            int end = txt.indexOf("\"", bgn + 1);
            if (end == -1) break;
            
            String strLiterals = txt.substring(bgn, end + 1);
            strLiterals = strLiterals.replaceAll("</*[^<>]+>", "");
            strLiterals = strLiterals.replace("//", "__SLASH_SLASH__");
            strLiterals = "<font color=\"#a3a3a3\">" + strLiterals + "</font>";
            
            txt = txt.substring(0, bgn) + strLiterals + txt.substring(end + 1);
            bgn += strLiterals.length();
        }
        
        // 3. Process multi-line /* ... */ comments (green)
        bgn = 0;
        while (true) {
            bgn = txt.indexOf("/*", bgn == 0 ? 0 : bgn + 1);
            if (bgn == -1) break;
            int end = txt.indexOf("*/", bgn + 2);
            if (end == -1) end = txt.length();
            
            String multiComment = txt.substring(bgn, end + 2);
            multiComment = multiComment.replaceAll("</*[^<>]+>", "");
            multiComment = "<font color=\"#009900\">" + multiComment + "</font>";
            
            txt = txt.substring(0, bgn) + multiComment + txt.substring(end + 2);
            bgn += multiComment.length();
        }
        
        // Process single-line // comments (green)
        bgn = 0;
        while (true) {
            bgn = txt.indexOf("//", bgn == 0 ? 0 : bgn + 1);
            if (bgn == -1) break;
            int end = txt.indexOf("<br>", bgn);
            if (end == -1) end = txt.length();
            
            String comment = txt.substring(bgn, end);
            comment = comment.replaceAll("</*[^<>]+>", "");
            comment = "<font color=\"#009900\">" + comment + "</font>";
            
            txt = txt.substring(0, bgn) + comment + txt.substring(end);
            bgn += comment.length();
        }
        
        // Restore // in string literals
        txt = txt.replace("__SLASH_SLASH__", "//");
        
        // Output the final HTML
        System.out.println("<html>\r\n<body>\r\n<tt>\r\n");
        System.out.println(txt);
        System.out.println("\r\n</tt>\r\n</body>\r\n</html>");
    }
}

How to Enable & Use the Tool

  1. Compile the class: Run javac java2colorHTML.java in your terminal.
  2. Run the converter: Execute java java2colorHTML YourJavaFile.java > output.html. This will generate an HTML file with colored Java code.
  3. View the result: Open output.html in any web browser to see your syntax-highlighted Java code.

内容的提问来源于stack exchange,提问作者BrYan Hsieh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:52:35