Java 实现的内容搜索工具

package com.ctl.util;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author ctl
 */
public class FileSearchJFrame extends javax.swing.JFrame {

    /**
     * Creates new form FileSearchJFrame
     */
    public FileSearchJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        filePath = new javax.swing.JTextField();
        Search = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        fileStorepath = new javax.swing.JTextField();
        CopyContainPath = new javax.swing.JButton();
        CopyNotContainPath = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        allSearchFileList = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        isContainChildDir = new javax.swing.JCheckBox();
        jLabel4 = new javax.swing.JLabel();
        isCaseSentive = new javax.swing.JCheckBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        allSearchRexFileList = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        layers = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        keyWord = new javax.swing.JTextField();
        sotpSearch = new javax.swing.JButton();
        expendAll = new javax.swing.JButton();
        foldAll = new javax.swing.JButton();
        copyJTreeSelected = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        filesTree = new javax.swing.JTree();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItemLoadProperties = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(199, 237, 204));

        filePath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                filePathActionPerformed(evt);
            }
        });

        Search.setText("Search");
        Search.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SearchMouseClicked(evt);
            }
        });
        Search.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SearchActionPerformed(evt);
            }
        });

        jLabel1.setText("FilePath:");

        jLabel2.setText("FileStorePath:");

        fileStorepath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileStorepathActionPerformed(evt);
            }
        });

        CopyContainPath.setText("CopyWithPath");
        CopyContainPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CopyContainPathActionPerformed(evt);
            }
        });

        CopyNotContainPath.setText("CopyWithoutPath");
        CopyNotContainPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CopyNotContainPathActionPerformed(evt);
            }
        });

        allSearchFileList.setEditable(false);
        allSearchFileList.setColumns(20);
        allSearchFileList.setRows(5);
        jScrollPane1.setViewportView(allSearchFileList);

        jLabel3.setText("Contain Child Dir:");

        jLabel4.setText("Case sentive:");

        allSearchRexFileList.setEditable(false);
        allSearchRexFileList.setColumns(20);
        allSearchRexFileList.setRows(5);
        jScrollPane2.setViewportView(allSearchRexFileList);

        jLabel5.setText(" remove layers:");

        layers.setText("1");

        jLabel6.setText("key word:");

        sotpSearch.setText("Stop");
        sotpSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                sotpSearchMouseClicked(evt);
            }
        });
        sotpSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sotpSearchActionPerformed(evt);
            }
        });

        expendAll.setText("ExpendAll");
        expendAll.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                expendAllMouseClicked(evt);
            }
        });

        foldAll.setText("FoldAll");
        foldAll.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                foldAllMouseClicked(evt);
            }
        });

        copyJTreeSelected.setText("CopyJTreeSelectedToClipboard");
        copyJTreeSelected.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                copyJTreeSelectedMouseClicked(evt);
            }
        });

        jButton1.setText("SearchDirectory");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel1))
                        .addGap(4, 4, 4)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(filePath, javax.swing.GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(keyWord, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(isContainChildDir)
                                .addGap(12, 12, 12)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(isCaseSentive)
                                .addGap(13, 13, 13)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(sotpSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(Search, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(1, 1, 1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(layers, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CopyContainPath)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(copyJTreeSelected)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(foldAll)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(expendAll))))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fileStorepath)
                .addGap(18, 18, 18)
                .addComponent(CopyNotContainPath))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(filePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Search))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(keyWord, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(isContainChildDir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(isCaseSentive, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(sotpSearch))
                .addGap(5, 5, 5)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(fileStorepath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CopyNotContainPath))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                .addGap(5, 5, 5)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CopyContainPath)
                    .addComponent(jLabel5)
                    .addComponent(layers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(expendAll)
                    .addComponent(foldAll)
                    .addComponent(copyJTreeSelected)
                    .addComponent(jButton1)))
        );

        DefaultMutableTreeNode root=new DefaultMutableTreeNode();
        root.setUserObject("root");
        DefaultTreeModel model=new DefaultTreeModel(root);
        filesTree.setModel(model);
        filesTree.addTreeSelectionListener(new TreeSelectionListener(){
            public void valueChanged(TreeSelectionEvent evt){
                DefaultMutableTreeNode note=(DefaultMutableTreeNode)filesTree.getLastSelectedPathComponent();
                final TreePath paths[]=filesTree.getSelectionPaths();
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                Transferable contents = new Transferable() {
                    DataFlavor[] dataFlavors = new DataFlavor[] { DataFlavor.javaFileListFlavor };
                    public Object getTransferData(DataFlavor flavor)throws UnsupportedFlavorException, IOException {
                        java.util.List<File> files = new ArrayList<File>();
                        for(TreePath path:paths){
                            TreeNode node=(TreeNode)path.getLastPathComponent();
                            files.add(new File(allSearchRexMap.get(node.toString())));
                        }
                        return files;
                    }
                    public DataFlavor[] getTransferDataFlavors() {
                        return dataFlavors;
                    }
                    public boolean isDataFlavorSupported(DataFlavor flavor) {
                        for (int i = 0; i < dataFlavors.length; i++) {
                            if (dataFlavors[i].equals(flavor)) {
                                return true;
                            }
                        }
                        return false;
                    }
                };
                clipboard.setContents(contents, null);
            }
        });
        jScrollPane3.setViewportView(filesTree);

        jMenu1.setText("File");

        jMenuItemLoadProperties.setText("Load Properties");
        jMenuItemLoadProperties.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLoadPropertiesActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItemLoadProperties);

        jMenuItem1.setText("Version");
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        jMenuItem2.setText("jMenuItem2");
        jMenu2.add(jMenuItem2);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void fileStorepathActionPerformed(java.awt.event.ActionEvent evt) {                                              

    }                                             

    private void filePathActionPerformed(java.awt.event.ActionEvent evt) {                                         

    }                                        

    private void CopyNotContainPathActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        fileStorepathStr = fileStorepath.getText();
        File file = new File(fileStorepathStr);
        if (fileStorepathStr == null || "".equals(fileStorepathStr.trim())) {
            File dir = new File("search");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file = dir;
        } else {
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        if (!file.isDirectory() || allSearchRexMap.size() < 0) {
            return;
        }
        Set<String> files = allSearchRexMap.keySet();
        Iterator<String> ito = files.iterator();
        while (ito.hasNext()) {
            String fileName = ito.next();
            String fileNamePath = allSearchRexMap.get(fileName);
            if (fileStorepathStr == null || "".equals(fileStorepathStr.trim())) {
                fileNamePath = file + File.separator + fileName;
            } else {
                fileNamePath = fileStorepathStr + File.separator + fileName;
            }
            byte[] buf = new byte[2048];
            try {
                InputStream in = new FileInputStream(allSearchRexMap.get(fileName));
                BufferedInputStream inBuf = new BufferedInputStream(in);
                OutputStream out = new FileOutputStream(new File(fileNamePath), false);
                BufferedOutputStream outBuf = new BufferedOutputStream(out);
                int read = 1;
                try {
                    while (read > 0) {
                        read = inBuf.read(buf);
                        outBuf.write(buf, 0, read);
                        outBuf.flush();
                        read = inBuf.available();
                    }
                    outBuf.close();
                    out.close();
                    inBuf.close();
                    in.close();
                } catch (Exception e) {
                    return;
                }
            } catch (Exception e) {
                return;
            }
        }
    }                                                  

    private void SearchActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:

    }                                      

    private void CopyContainPathActionPerformed(java.awt.event.ActionEvent evt) {                                                
        fileStorepathStr = fileStorepath.getText();
        File file = new File(fileStorepathStr);
        if (fileStorepathStr == null || "".equals(fileStorepathStr.trim())) {
            File dir = new File("search");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file = dir;
        } else {
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        if (!file.isDirectory() || allSearchRexMap.size() < 0) {
            return;
        }
        int layersi = 1;
        try {
            layersi = Integer.parseInt(layers.getText());
            Set<String> files = allSearchRexMap.keySet();
            Iterator<String> ito = files.iterator();
            while (ito.hasNext()) {
                String fileName = ito.next();
                String fileNamePath = allSearchRexMap.get(fileName);
                int index = -1;
                for (int i = 0; i < layersi; i++) {
                    index = fileNamePath.indexOf("\\", index + 1);
                }
                fileNamePath = fileNamePath.substring(index);
                if (fileStorepathStr == null || "".equals(fileStorepathStr.trim())) {
                    fileNamePath = file + fileNamePath;
                } else {
                    fileNamePath = fileStorepathStr + fileNamePath;
                }
                File f = new File(fileNamePath);
                File fileStore = new File(f.getParent());
                if (!fileStore.exists()) {
                    fileStore.mkdirs();
                }
                byte[] buf = new byte[2048];
                try {
                    InputStream in = new FileInputStream(allSearchRexMap.get(fileName));
                    BufferedInputStream inBuf = new BufferedInputStream(in);
                    OutputStream out = new FileOutputStream(new File(fileNamePath), false);
                    BufferedOutputStream outBuf = new BufferedOutputStream(out);
                    int read = 1;
                    try {
                        while (read > 0) {
                            read = inBuf.read(buf);
                            outBuf.write(buf, 0, read);
                            outBuf.flush();
                            read = inBuf.available();
                        }
                        outBuf.close();
                        out.close();
                        inBuf.close();
                        in.close();
                    } catch (Exception e) {
                        return;
                    }
                } catch (Exception e) {
                    return;
                }
            }
        } catch (Exception e) {
            return;
        }
    }                                               

    private void sotpSearchActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void SearchMouseClicked(java.awt.event.MouseEvent evt) {                                    
        runFlag = true;
        class RunSearchThread implements Runnable {

            public void run() {
                String searchPath = filePath.getText();
                fileStorepathStr = fileStorepath.getSelectedText();
                isCaseSentiveBool = isCaseSentive.isSelected();
                isContainChildDirBool = isContainChildDir.isSelected();
                layersStr = layers.getText();
                if (layersStr == null || "".equals(layersStr.trim())) {
                    layersStr = "1";
                }
                keywordStr = keyWord.getText();
                if (searchPath == null || "".endsWith(searchPath.trim()) || keywordStr == null || "".equals(keywordStr.trim())) {
                    return;
                }
                keywordStr = keywordStr.trim();
                Properties config = new Properties();
                try {
                    config.load(FileSearchJFrame.class.getClassLoader().getResourceAsStream("pro.properties"));
                    //  types=config.getProperty("filetype").split("\\|");
                    types = config.getProperty("filetype");
                    System.err.println(types);
                    allSearchFileList.setFont(new Font("\u6977\u4F53 ", 10, 11));
                    allSearchFileList.setWrapStyleWord(true);// \u6FC0\u6D3B\u65AD\u884C\u4E0D\u65AD\u5B57\u529F\u80FD
                    allSearchFileList.setLineWrap(true);
                    allSearchRexFileList.setFont(new Font("\u6977\u4F53 ", 10, 11));
                    allSearchRexFileList.setWrapStyleWord(true);// \u6FC0\u6D3B\u65AD\u884C\u4E0D\u65AD\u5B57\u529F\u80FD
                    allSearchRexFileList.setLineWrap(true);
                    allSearch.delete(0, allSearch.length());
                    allSearchRex.delete(0, allSearchRex.length());
                    //   allSearchRexList.clear();
                    allSearchRexMap.clear();
                    listAllFliesAndDir(searchPath, isContainChildDirBool);
                    allSearchFileList.setText(allSearch.toString());
                    allSearchRexFileList.setText(allSearchRex.toString());

                    Set<String> keys = allSearchRexMap.keySet();
                    Iterator<String> iter = keys.iterator();
                    Set<String> fileDirs = new TreeSet<>();
                    while (iter.hasNext() && runFlag) {
                        String key = iter.next();
                        String value = allSearchRexMap.get(key);
                        int index = -1;
                        // //System.out.println(value);
                        for (int i = 0; i < value.split("\\\\").length - 1 && runFlag; i++) {
                            index = value.indexOf("\\", index + 1);
                            String fileDir = value.substring(0, index);
                            //  //System.out.println(fileDir);
                            //  System.err.println(value.substring(index+1));
                            //  fileDirs.add(fileDir+StringUtils.leftPad(String.valueOf(index), 4, '0'));
                            fileDirs.add(fileDir);
                        }
                    }
                    Iterator<String> fileDirsIter = fileDirs.iterator();
                    Set<String> set1 = new TreeSet<>();
                    while (fileDirsIter.hasNext() && runFlag) {
                        String fileDir = fileDirsIter.next();
                        //System.err.println(fileDir+"\t【layers】:"+fileDir.split("\\\\").length);
                        set1.add(StringUtils.leftPad(String.valueOf(fileDir.split("\\\\").length), 4, '0') + fileDir);
                    }

                    Iterator<String> iter1 = set1.iterator();
                    Map<Integer, DefaultMutableTreeNode> treeNodeMap = new HashMap<>();
                    //创建对象

                    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
                    while (iter1.hasNext() && runFlag) {
                        String fileDir = iter1.next();
                        String layerStr = fileDir.substring(0, 4);
                        int layer = Integer.parseInt(layerStr);
                        if (layer == 1) {
                            System.err.println(fileDir + "\t【" + fileDir.substring(4) + "】  本节点:" + fileDir.substring(4).hashCode());
                            rootNode.setUserObject(fileDir.substring(4));
                            treeNodeMap.put(fileDir.substring(4).hashCode(), rootNode);
                        } else {
                            int thisPoint = fileDir.substring(4).hashCode();
                            int parentPoint = fileDir.substring(4, fileDir.indexOf(fileDir.split("\\\\")[layer - 1]) - 1).hashCode();
                            System.err.println(fileDir + "\t【" + fileDir.split("\\\\")[layer - 1] + "】 本节点:" + thisPoint + "  父节点:" + parentPoint);
                            DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode();
                            leafNode.setUserObject(fileDir.split("\\\\")[layer - 1]);
                            treeNodeMap.put(thisPoint, leafNode);
                            treeNodeMap.get(parentPoint).add(leafNode);
                        }
                    }
                    Iterator<String> iterFiles = keys.iterator();
                    while (iterFiles.hasNext() && runFlag) {
                        String key = iterFiles.next();
                        String value = allSearchRexMap.get(key);
                        File file = new File(value);
                        String path = file.getParent();
                        DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode();
                        leafNode.setUserObject(key);
                        treeNodeMap.get(path.hashCode()).add(leafNode);
                    }
                    DefaultTreeModel model = new DefaultTreeModel(rootNode);
                    filesTree.setModel(model);
                    filesTree.collapsePath(new TreePath(rootNode));

                } catch (IOException e) {
                    System.err.println(e.getMessage());
                }
            }
        }
        RunSearchThread run = new RunSearchThread();
        Thread th = new Thread(run);
        th.start();
    }                                   

    private void sotpSearchMouseClicked(java.awt.event.MouseEvent evt) {                                        
        runFlag = false;
    }                                       

    private void expendAllMouseClicked(java.awt.event.MouseEvent evt) {                                       
        TreeNode root = (TreeNode) filesTree.getModel().getRoot();
        expandAll(filesTree, new TreePath(root), true);
    }                                      

    private void foldAllMouseClicked(java.awt.event.MouseEvent evt) {                                     
        TreeNode root = (TreeNode) filesTree.getModel().getRoot();
        expandAll(filesTree, new TreePath(root), false);
    }                                    

    private void copyJTreeSelectedMouseClicked(java.awt.event.MouseEvent evt) {                                               

    }                                              

    private void jMenuItemLoadPropertiesActionPerformed(java.awt.event.ActionEvent evt) {                                                        
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setCurrentDirectory(new File("."));
        fileChooser.setMultiSelectionEnabled(true);
        fileChooser.showOpenDialog(null);
        fileChooser.setApproveButtonText("Confirm");
        fileChooser.setDialogTitle("Open File") ;
        File[] files=fileChooser.getSelectedFiles();
        for(File file:files){
          ;
        }
    }                                                       

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
     JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
         fileChooser.setMultiSelectionEnabled(false);
         fileChooser.setApproveButtonText("Confirm");
         fileChooser.setDialogTitle("Open File") ; 
         fileChooser.showOpenDialog(null);
         File file=fileChooser.getSelectedFile();
         if(file!=null&&!"".equals(file)){
        	 filePath.setText(file.getPath());
         }
    }                                     
    private void expandAll(JTree tree, TreePath parent, boolean expand) {
        TreeNode node = (TreeNode) parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                TreeNode n = (TreeNode) e.nextElement();
                TreePath path = parent.pathByAddingChild(n);
                expandAll(tree, path, expand);
            }
        }
        if (expand) {
            tree.expandPath(parent);
        } else {
            tree.collapsePath(parent);
        }
    }

    public void listAllFliesAndDir(String filePath, boolean childDir) {
        if (!runFlag) {
            return;
        }
        File file = new File(filePath);
        // File f = new File(file.getParent());
        // //System.out.println(file);
        if (!file.isDirectory()) {
            return;
        } else {
            String fileList[] = file.list();
            for (String s : fileList) {
                if (!runFlag) {
                    return;
                }
                // //System.out.println(file + File.separator + s);
                File file1 = new File(file + File.separator + s);
                if (file1.isFile()) {
                    String tmp = "\u6587\u4EF6:" + file + File.separator + s;
                    //System.out.println(tmp);
                    allSearch.append(tmp).append("\n");
                    String[] ends = s.split("\\.");
                    if (ends.length == 2 && types.contains(ends[1])) {
                        Scanner scanner = null;
                        try {
                            scanner = new Scanner(new FileInputStream(file + File.separator + s));
                        } catch (Exception e) {
                            return;
                        }
                        boolean contain = false;
                        while (scanner.hasNext() && runFlag) {
                            String value = scanner.nextLine();
                            if (isCaseSentiveBool) {
                                if (value.contains(keywordStr)) {
                                    contain = true;
                                    break;
                                }
                            } else {
                                if (value.toLowerCase().contains(keywordStr.toLowerCase())) {
                                    contain = true;
                                    break;
                                }
                            }
                        }
                        scanner.close();
                        if (contain) {
                            allSearchRex.append(file).append(File.separator).append(s).append("\n");
                            // allSearchRexList.add(file + File.separator+ s);
                            if (allSearchRexMap.containsKey(s)) {
                                allSearchRexMap.put(s + "." + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()), file + File.separator + s);
                            } else {
                                allSearchRexMap.put(s, file + File.separator + s);
                            }
                        }
                    }
                    continue;
                }
                if (file1.isDirectory() && childDir && file1.list().length > 0) {
                    String tmp = "\u76EE\u5F55:" + file + File.separator + s;
                    //System.out.println(tmp);
                    allSearch.append(tmp).append("\n");
                    listAllFliesAndDir(file + File.separator + s, childDir);
                }

                if (file1.isDirectory() && childDir && file1.list().length == 0) {
                    String tmp = "\u76EE\u5F55:" + file + File.separator + s;
                    //System.out.println(tmp);
                    allSearch.append(tmp).append("\n");
                }

            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FileSearchJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FileSearchJFrame().setVisible(true);
            }
        });
    }
    private static Boolean runFlag;
    private String fileStorepathStr;
    private Boolean isCaseSentiveBool;
    private Boolean isContainChildDirBool;
    private String layersStr;
    private String keywordStr;
    private String types;
    private final StringBuilder allSearch = new StringBuilder(10000);
    private final StringBuilder allSearchRex = new StringBuilder(3000);
    //  private static List<String>  allSearchRexList=new ArrayList<String>(300);
    private final Map<String, String> allSearchRexMap = new HashMap<>();
    // Variables declaration - do not modify                     
    private javax.swing.JButton CopyContainPath;
    private javax.swing.JButton CopyNotContainPath;
    private javax.swing.JButton Search;
    private javax.swing.JTextArea allSearchFileList;
    private javax.swing.JTextArea allSearchRexFileList;
    private javax.swing.JButton copyJTreeSelected;
    private javax.swing.JButton expendAll;
    private javax.swing.JTextField filePath;
    private javax.swing.JTextField fileStorepath;
    private javax.swing.JTree filesTree;
    private javax.swing.JButton foldAll;
    private javax.swing.JCheckBox isCaseSentive;
    private javax.swing.JCheckBox isContainChildDir;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItemLoadProperties;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField keyWord;
    private javax.swing.JTextField layers;
    private javax.swing.JButton sotpSearch;
    // End of variables declaration                   

}

filetype=xml|java|jsp|properties|prop|txt|TXT|html|htm|js|css

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值