为你的Java代码批量设置头注释

类别:Java 点击:0 评论:0 推荐:

大多正式一点的Java源代码,在头部都设有头注释信息,其中包含一些版权声明等信息。例如JDK的源码一般如下:

/*
 * @(#)Object.java 1.61 03/01/23
 *
 * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

public class Object { .....}

如果我们有个小工具能把我们项目里所有目录下的Java代码统一设置头注释就好了;比如当版本信息等改变时,只要重新运行一下即可一次性更新。下面我们就来亲自写一个。

思路很简单:

建立一个窗口,用户可以设置一个目录、编写头注释信息; 查找目录下所有子文件,如果是Java文件则处理之,如果是目录则递归处理; 处理Java文件时,打开后,找到package语句或者第一个import语句,作为注释的插入点,插入注释; 将增加了头注释的文件内容写回文件。

本例中判断头注释插入点的逻辑比较简单,只是根据package语句或者第一个import语句来判断注释插入点,尚不严谨(比如原有的头注释中可能包含这些关键字),仅供参考。

源码如下:

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HeaderCommentsGenerator {
    private static int count = 0;

    public static void main(String[] args) {
        final JFrame frame = new JFrame("HeaderCommentsGenerator 1.0 [[email protected]]");
        JPanel contentPane = (JPanel) frame.getContentPane();
        JPanel centerPane = new JPanel(new BorderLayout(10, 10));
        centerPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
        JPanel pathPane = new JPanel(new BorderLayout());
        final JTextField txtPath = new JTextField();
        txtPath.setText("Please select your file or path.");
        pathPane.add(txtPath, BorderLayout.CENTER);
        JButton btnSelectPath = new JButton("Browser...");
        btnSelectPath.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                int returnVal = chooser.showOpenDialog(frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    txtPath.setText(chooser.getSelectedFile().getAbsolutePath());
                }
            }
        });
        btnSelectPath.setMnemonic('B');
        pathPane.add(btnSelectPath, BorderLayout.EAST);
        centerPane.add(pathPane, BorderLayout.NORTH);
        final JTextArea txtComments = new JTextArea();
        txtComments.setText("/*\n" +
                            " * Copyright 2003-2004 ABC Software, Inc. All rights reserved.\n" +
                            " */");
        centerPane.add(new JScrollPane(txtComments), BorderLayout.CENTER);

        contentPane.add(centerPane, BorderLayout.CENTER);

        JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        JButton btnOK = new JButton("Generate!");
        btnOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String path = txtPath.getText();
                File file = new File(path);
                if (!file.exists()) {
                    JOptionPane.showMessageDialog(frame,
                                                  "Path '" + path + "' not exist.",
                                                  "Error",
                                                  JOptionPane.ERROR_MESSAGE);
                } else {
                    commentFile(file, txtComments.getText());
                    JOptionPane.showMessageDialog(frame,
                                                  "Finish, total " + count + " files are processed.",
                                                  "Information",
                                                  JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
        btnOK.setMnemonic('G');
        JButton btnClose = new JButton("Close");
        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        btnClose.setMnemonic('C');
        buttonPane.add(btnOK);
        buttonPane.add(btnClose);
        contentPane.add(buttonPane, BorderLayout.SOUTH);

        frame.setSize(500, 300);
        frame.show();
    }

    private static void commentFile(File file, String comments) {
        if (file != null && file.exists()) {
            if (file.isDirectory()) {
                String[] children = file.list();
                for (int i = 0; i < children.length; i++) {
                    File child = new File(file.getPath() + System.getProperty("file.separator") + children[i]);
                    commentFile(child, comments);
                }
            } else {
                if (file.getName().toLowerCase().endsWith(".java")) {
                    System.out.println(file.getName());
                    count++;
                    try {
                        RandomAccessFile raFile = new RandomAccessFile(file, "rw");
                        byte[] content = new byte[ (int) raFile.length()];
                        raFile.readFully(content);
                        String all = new String(content);
                        all = all.trim();
                        while (all.startsWith("\n")) {
                            all = all.substring(1);
                        }
                        if (all.indexOf("package") != -1) {
                            all = all.substring(all.indexOf("package"));
                        }
                        if (all.indexOf("import") != -1) {
                            all = all.substring(all.indexOf("package"));
                        }
                        all = comments + "\n" + all;
                        raFile.close();
                        FileWriter writer = new FileWriter(file);
                        writer.write(all);
                        writer.close();
                    }
                    catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
}

希望这个小工具对你有点用处。

本文地址:http://com.8s8s.com/it/it15452.htm