【Java练习】文本处理:HTML生成器、CD-Key生成器、正则表达式查询工具

需求

HTML生成器

  • 将 TEXT 文档转换成HTML文件,对制作网页HTML文档很有用

CD-Key生成器

  • 利用某种算法生成一个唯一的key。软件开发者可以用它来作为软件的激活器

正则表达式查询工具

  • 用户可以输入一段文本,在另外的控件里输入一个正则表达式。运行以后会返回匹配的内容或者正则表达式中的错误

思路

HTML生成器:
读取文件后添加html头尾,中间每一行遍历出来加

标签

CD-Key生成器:
使用SecureRandom生成随机数

正则表达式查询工具:
没什么好说的,匹配就完事了

实现

  • HTML生成器
public class TextToHtmlConverter extends JFrame {

    private JTextField textFilePathField;
    private JButton browseButton;
    private JButton convertButton;
    private JFileChooser fileChooser;

    public TextToHtmlConverter(){
        //窗体
        setTitle("文本转html器");
        setSize(400, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        //组件
        textFilePathField = new JTextField();
        browseButton = new JButton("选择");
        browseButton.addActionListener(e -> choseFile());
        convertButton = new JButton("转化");
        convertButton.addActionListener(e -> convertToHtml());
        fileChooser = new JFileChooser();

        //布局
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(textFilePathField, BorderLayout.CENTER);
        topPanel.add(browseButton, BorderLayout.EAST);

        //放到主类里
        add(topPanel, BorderLayout.NORTH);
        add(convertButton, BorderLayout.SOUTH);

    }


    public void choseFile(){
        int returnValue = fileChooser.showOpenDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            textFilePathField.setText(selectedFile.getAbsolutePath());
        }
    }

    private void convertToHtml() {
        String path = textFilePathField.getText();
        if(path.isEmpty()){
            JOptionPane.showMessageDialog(this, "先选文件",
                    "注意",JOptionPane.ERROR_MESSAGE);
            return;
        }

        File file = new File(path);
        if(!file.exists()){
            JOptionPane.showMessageDialog(this, "找不到文件,重新选一下",
                    "注意",JOptionPane.ERROR_MESSAGE);
            return;
        }

        //重命名
        String htmlFileName = file.getName().replace(".txt", ".html");
        //这么创建文件就与txt文件同路径
        File htmlFile = new File(file.getParent(), htmlFileName);
        //try with catch
        try(BufferedReader reader = new BufferedReader(new FileReader(file));
            PrintWriter writer = new PrintWriter(new FileWriter(htmlFile))) {
            writer.println("<html>");
            writer.println("<body>");
            writer.println("<head><title>" + file.getName() + "</title></head>");

            String line;
            while((line = reader.readLine()) != null){
                writer.println("<p>" + line + "</p>");
            }

            writer.println("</body>");
            writer.println("</html>");

            JOptionPane.showMessageDialog(this, "转换完成",
                    "提示",JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(this, "转换出现问题",
                    "错误",JOptionPane.ERROR_MESSAGE);
        }

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TextToHtmlConverter().setVisible(true));
    }
}

  • CD-Key生成器

public class CDKeyGenerator extends JFrame {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int KEY_LENGTH = 5;
    private static final int PARTS = 4;

    private JTextArea keyDisplayArea;
    private JButton generateButton;
    private JButton copyButton;

    public CDKeyGenerator(){
        setTitle("CD-Key 生成器");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        keyDisplayArea = new JTextArea();
        keyDisplayArea.setFont(new Font("Monospaced", Font.BOLD, 20));
        keyDisplayArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(keyDisplayArea);

        generateButton = new JButton("生成");
        generateButton.addActionListener(e -> generateCDKey());

        copyButton = new JButton("复制");
        copyButton.addActionListener(e -> copyCDKey());

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(generateButton);
        buttonPanel.add(copyButton);


        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void generateCDKey() {
        SecureRandom secureRandom = new SecureRandom();
        StringBuilder keyBuilder = new StringBuilder();

        for (int i = 0; i < PARTS; i++){
            if(i > 0){
                keyBuilder.append("-");
            }

            for(int j = 0; j < KEY_LENGTH; j++){
                int index = secureRandom.nextInt(CHARACTERS.length());
                keyBuilder.append(CHARACTERS.charAt(index));
            }
        }

        keyDisplayArea.setText(keyBuilder.toString());
    }

    private void copyCDKey() {
        String key = keyDisplayArea.getText();
        if(key.isEmpty()){
            JOptionPane.showMessageDialog(this, "没有CD-Key,先生成",
                    "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        //选中字符
        StringSelection selection = new StringSelection(key);
        //剪切板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        //写进剪切板
        clipboard.setContents(selection, selection);

        JOptionPane.showMessageDialog(this, "复制成功",
                "提示", JOptionPane.INFORMATION_MESSAGE);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new CDKeyGenerator().setVisible(true));
    }
}

正则表达式查询工具:

public class RegexQueryTool extends JFrame {

    private JTextArea textInputArea;
    private JTextField regexInputField;
    private JTextArea resultArea;
    private JButton runButton;

    public RegexQueryTool(){
        setTitle("正则工具");
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        textInputArea = new JTextArea();
        regexInputField = new JTextField();
        resultArea = new JTextArea();
        resultArea.setEditable(false);
        runButton = new JButton("运行");

        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(new JLabel("文本:"), BorderLayout.NORTH);
        inputPanel.add(new JScrollPane(textInputArea), BorderLayout.CENTER);

        JPanel regexPanel = new JPanel(new BorderLayout());
        regexPanel.add(new JLabel("正则:"), BorderLayout.WEST);
        regexPanel.add(regexInputField, BorderLayout.CENTER);

        JPanel resultPanel = new JPanel(new BorderLayout());
        resultPanel.add(new JLabel("结果:"), BorderLayout.NORTH);
        resultPanel.add(new JScrollPane(resultArea), BorderLayout.CENTER);

        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(inputPanel, BorderLayout.CENTER);
        topPanel.add(regexPanel, BorderLayout.SOUTH);

        add(topPanel, BorderLayout.CENTER);
        add(runButton, BorderLayout.SOUTH);
        add(resultPanel, BorderLayout.EAST);

        runButton.addActionListener(e -> runRegex());
    }

    private void runRegex() {
        String text = textInputArea.getText();
        String regex = regexInputField.getText();

        try{
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);

            StringBuilder results = new StringBuilder();
            while (matcher.find()) {
                results.append("匹配到: ").append(matcher.group()).append("\n");
            }
            if (results.length() == 0) {
                results.append("没有匹配");
            }

            resultArea.setText(results.toString());
        }catch (PatternSyntaxException e){
            resultArea.setText("正则错误: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        /**
         * 测试用例:
         * Hello, this is a sample text.
         * Let's test some regular expressions!
         * Email me at example@example.com.
         * Call me at 123-456-7890.
         * The quick brown fox jumps over the lazy dog.
         *
         * 测试正则:
         * \b\w{5}\b
         */
        SwingUtilities.invokeLater(() -> new RegexQueryTool().setVisible(true));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值