JEditorPaneHTMLEditorKitParserByte字节处理

wen java案例 2

本文目录导读:

JEditorPaneHTMLEditorKitParserByte字节处理

  1. 基本设置与字节编码
  2. 字节流读取HTML内容
  3. 读取本地HTML文件
  4. 字节分析和处理
  5. 实际应用示例
  6. 性能优化建议
  7. 常见问题处理

对于 JEditorPane 和 HTMLEditorKit 的字节处理,主要涉及以下几个关键方面:

基本设置与字节编码

import javax.swing.*;
import javax.swing.text.html.*;
import java.io.*;
public class HTMLByteEditor {
    public static void main(String[] args) {
        JEditorPane editor = new JEditorPane();
        editor.setEditorKit(new HTMLEditorKit());
        editor.setContentType("text/html; charset=UTF-8");
        // 设置HTML内容
        String html = "<html><body><h1>测试</h1></body></html>";
        editor.setText(html);
    }
}

字节流读取HTML内容

// 从字节流读取
public void loadFromBytes(JEditorPane editor, byte[] htmlBytes) throws Exception {
    // 直接方式
    String html = new String(htmlBytes, "UTF-8");
    editor.setText(html);
    // 通过流的方式
    try (ByteArrayInputStream bais = new ByteArrayInputStream(htmlBytes)) {
        HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
        Document doc = kit.createDefaultDocument();
        kit.read(bais, doc, 0);
        editor.setDocument(doc);
    }
}

读取本地HTML文件

public void loadFromFile(JEditorPane editor, String filePath) {
    try {
        // 读取文件字节
        File file = new File(filePath);
        byte[] fileBytes = Files.readAllBytes(file.toPath());
        // 检测BOM(字节顺序标记)
        String encoding = detectEncoding(fileBytes);
        String html = new String(fileBytes, encoding);
        editor.setText(html);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private String detectEncoding(byte[] bytes) {
    if (bytes.length >= 3 && bytes[0] == (byte)0xEF && bytes[1] == (byte)0xBB && bytes[2] == (byte)0xBF) {
        return "UTF-8";
    } else if (bytes.length >= 2 && bytes[0] == (byte)0xFE && bytes[1] == (byte)0xFF) {
        return "UTF-16BE";
    } else if (bytes.length >= 2 && bytes[0] == (byte)0xFF && bytes[1] == (byte)0xFE) {
        return "UTF-16LE";
    }
    return "UTF-8"; // 默认
}

字节分析和处理

public class HTMLByteProcessor {
    // 分析HTML字节
    public static void analyzeHTMLBytes(byte[] htmlBytes) {
        System.out.println("字节总长度: " + htmlBytes.length);
        System.out.println("前20个字节: ");
        for (int i = 0; i < Math.min(20, htmlBytes.length); i++) {
            System.out.printf("%02X ", htmlBytes[i] & 0xFF);
        }
        System.out.println();
    }
    // 查找特定的字节模式
    public static List<Integer> findPattern(byte[] data, byte[] pattern) {
        List<Integer> positions = new ArrayList<>();
        for (int i = 0; i <= data.length - pattern.length; i++) {
            boolean found = true;
            for (int j = 0; j < pattern.length; j++) {
                if (data[i + j] != pattern[j]) {
                    found = false;
                    break;
                }
            }
            if (found) {
                positions.add(i);
            }
        }
        return positions;
    }
    // 处理特殊字符的字节
    public static String handleSpecialBytes(byte[] htmlBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : htmlBytes) {
            if (b < 0) { // 非ASCII字符
                sb.append(String.format("&#%d;", b & 0xFF));
            } else {
                sb.append((char) b);
            }
        }
        return sb.toString();
    }
}

实际应用示例

public class HTMLEditorWithBytes extends JFrame {
    private JEditorPane editor;
    public HTMLEditorWithBytes() {
        setTitle("HTML字节编辑器");
        setSize(800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        editor = new JEditorPane();
        editor.setEditorKit(new HTMLEditorKit());
        editor.setContentType("text/html");
        JScrollPane scrollPane = new JScrollPane(editor);
        add(scrollPane, BorderLayout.CENTER);
        JButton loadButton = new JButton("加载HTML文件");
        loadButton.addActionListener(e -> loadHTMLFile());
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loadButton);
        add(buttonPanel, BorderLayout.NORTH);
    }
    private void loadHTMLFile() {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                File file = fileChooser.getSelectedFile();
                byte[] fileBytes = Files.readAllBytes(file.toPath());
                // 字节处理
                analyzeAndDisplayHTML(fileBytes);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "加载失败: " + ex.getMessage());
            }
        }
    }
    private void analyzeAndDisplayHTML(byte[] htmlBytes) throws Exception {
        // 分析字节
        HTMLByteProcessor.analyzeHTMLBytes(htmlBytes);
        // 查找所有HTML标签位置
        byte[] bodyTag = "<body".getBytes();
        List<Integer> positions = HTMLByteProcessor.findPattern(htmlBytes, bodyTag);
        System.out.println("找到 <body> 标签位置: " + positions);
        // 显示内容
        String html = new String(htmlBytes, "UTF-8");
        editor.setText(html);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new HTMLEditorWithBytes().setVisible(true);
        });
    }
}

性能优化建议

// 使用缓冲读取大文件
public String readLargeHTMLFile(File file) throws IOException {
    StringBuilder content = new StringBuilder();
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
         InputStreamReader reader = new InputStreamReader(bis, "UTF-8")) {
        char[] buffer = new char[8192];
        int charsRead;
        while ((charsRead = reader.read(buffer)) != -1) {
            content.append(buffer, 0, charsRead);
        }
    }
    return content.toString();
}
// 分批处理字节
public void processHTMLBytesInBatches(byte[] htmlBytes, int batchSize) {
    for (int i = 0; i < htmlBytes.length; i += batchSize) {
        int end = Math.min(i + batchSize, htmlBytes.length);
        byte[] batch = Arrays.copyOfRange(htmlBytes, i, end);
        // 处理这一批字节
        processBatch(batch, i);
    }
}
private void processBatch(byte[] batch, int startPosition) {
    // 实际处理逻辑
    String batchStr = new String(batch, StandardCharsets.UTF_8);
    // 更新UI(需要SwingUtilities.invokeLater)
}

常见问题处理

// 处理乱码问题
public String fixEncodingIssues(byte[] htmlBytes) {
    // 尝试多种编码
    String[] encodings = {"UTF-8", "GBK", "GB2312", "ISO-8859-1", "UTF-16"};
    for (String encoding : encodings) {
        try {
            String decoded = new String(htmlBytes, encoding);
            if (isValidHTML(decoded)) {
                return decoded;
            }
        } catch (Exception e) {
            continue;
        }
    }
    return new String(htmlBytes, StandardCharsets.UTF_8);
}
private boolean isValidHTML(String html) {
    // 简单验证
    return html.contains("<html") || html.contains("<body") || html.contains("<p");
}

这些示例涵盖了 JEditorPane 与 HTMLEditorKit 在处理字节时的常见场景,包括编码处理、文件操作、字节分析等,根据具体需求可以选择合适的方法。

抱歉,评论功能暂时关闭!