• java线程池 多线程 搜索包含关键字的文件路径


    package org.jimmy.searchfile20180807.main;
    
    public class ThreadMain implements Runnable{
    
        private int taskNum;
        private String searchDirPath;
        private String keyWords;
        
        public ThreadMain(int taskNum, String searchDirPath, String keyWords){
            this.taskNum = taskNum;
            this.searchDirPath = searchDirPath;
            this.keyWords = keyWords;
        }
        
        @Override
        public void run() {
            System.out.println("正在执行task " + taskNum);
            System.out.println("当前关键字:" + keyWords);
            SearchMain searchMain = new SearchMain(searchDirPath, keyWords);
            searchMain.search();
            System.out.println("task " + taskNum + "执行完毕");
        }
    
    }
    package org.jimmy.searchfile20180807.main;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    public class SearchMain {
    
        private String searchDirPath;
        private String keyWords;
        
        public SearchMain(String searchDirPath, String keyWords){
            this.searchDirPath = searchDirPath;
            this.keyWords = keyWords;
        }
        
        //计算文件数量
        public static int count = 0;
        
        public static FileOutputStream fos = null;
        
        /**
         * Author: Yuxin.Yang(Jimmy)
         * Time: 2018年8月7日 上午9:02:45
         * Detail: 查询包含关键字的文件的路径
         */
        public void search(){
            File file = new File(searchDirPath);
            File[] files = file.listFiles();
            getFiles(files);
            System.out.println("count:" + count);
        }
        
        //递归搜索文件并写入搜索到的路径到文件
        public void getFiles(File[] files){
            FileInputStream fis = null;
            try{
                for(File file : files){
                    count++;
                    if(file.isDirectory()){
                        getFiles(file.listFiles());
                    }else{
                        StringBuffer sb = new StringBuffer();
                        byte[] bytes = new byte[1024];
                        fis = new FileInputStream(file);
                        int len = 0;
                        while((len = fis.read(bytes)) != -1){
                            sb.append(new String(bytes, 0, len, "utf-8"));
                        }
                        fis.close();
                        if(sb.indexOf(keyWords) >= 0){
                            System.out.println("包含关键字(" + keyWords + ")的文件路径:" + file.getAbsolutePath());
                            fos.write(("包含关键字(" + keyWords + ")的文件路径:" + file.getAbsolutePath() + System.lineSeparator()).getBytes());
                            fos.flush();
                        }
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        
    }
    package org.jimmy.searchfile20180807.ui;
    
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    
    import org.jimmy.searchfile20180807.main.SearchMain;
    import org.jimmy.searchfile20180807.main.ThreadMain;
    
    public class SearchUi {
        
        public static void main(String[] args){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    SearchUi searchUi = new SearchUi();
                    searchUi.init();
                }
            });
            
        }
        
        public void init(){
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("搜索文件路径");
            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
            frame.setBounds(0, 0, (int) dimension.getWidth(), (int) dimension.getHeight());
            frame.setLayout(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            int scrollPaneWidth = (int) dimension.getWidth() - 15;
            int scrollPaneHeight = (int) dimension.getHeight() - 35;
            JPanel panel = new JPanel();
            panel.setLayout(null);
            panel.setBounds(0, 0, (int) dimension.getWidth(), (int) dimension.getHeight());
            //添加滚动条
            JScrollPane scrollPane = new JScrollPane(panel);
            scrollPane.setBounds(0, 0, scrollPaneWidth, scrollPaneHeight);
            scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            frame.add(scrollPane);
            
            //初始坐标
            int x = 0;
            int y = 0;
            
            //加上输入要搜索的文件夹路径的提示文本
            int height = 30;
            JLabel searchDirPathLabel = new JLabel("请输入要搜索的文件夹的路径:");
            searchDirPathLabel.setBounds(x, y, scrollPaneWidth, height);
            searchDirPathLabel.setHorizontalAlignment(JLabel.CENTER);
            panel.add(searchDirPathLabel);
                    
            //加上输入要搜索的文件夹路径的文本框
            y += height + 20;
            height = 100;
            final JTextArea searchDirPathText = new JTextArea();
            searchDirPathText.setBounds(x, y, scrollPaneWidth, height);
            panel.add(searchDirPathText);
            
            //加上输入路径的文本框的提示文本
            y += height + 20;
            height = 30;
            JLabel searchedFilePathLabel = new JLabel("请输入生成的搜索结果文件的路径:");
            searchedFilePathLabel.setBounds(x, y, scrollPaneWidth, height);
            searchedFilePathLabel.setHorizontalAlignment(JLabel.CENTER);
            panel.add(searchedFilePathLabel);
            
            //加上输入路径的文本框
            y += height + 20;
            height = 100;
            final JTextArea searchedFilePathText = new JTextArea();
            searchedFilePathText.setBounds(x, y, scrollPaneWidth, height);
            panel.add(searchedFilePathText);
            
            //加上输入关键字的文本框的提示文本
            y += height + 20;
            height = 30;
            JLabel keyWordsLabel = new JLabel("请输入需要搜索的关键字(如果有多个,用英文半角逗号隔开):");
            keyWordsLabel.setBounds(x, y, scrollPaneWidth, height);
            keyWordsLabel.setHorizontalAlignment(JLabel.CENTER);
            panel.add(keyWordsLabel);
                
            //加上输入关键字的文本框
            y += height + 20;
            height = 100;
            final JTextArea keyWordsText = new JTextArea();
            keyWordsText.setBounds(x, y, scrollPaneWidth, height);
            panel.add(keyWordsText);
            
            //加上搜索按钮
            y += height + 20;
            height = 30;
            int searchBtnWidth = 100;
            JButton searchBtn = new JButton("搜索");
            searchBtn.setBounds((scrollPaneWidth - searchBtnWidth) / 2, y, searchBtnWidth, height);
            searchBtn.setHorizontalAlignment(JButton.CENTER);
            searchBtn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String searchDirPath = searchDirPathText.getText().replaceAll(" ", "");
                    String searchedFilePath = searchedFilePathText.getText().replaceAll(" ", "");
                    File searchedFile = new File(searchedFilePath);
                    FileOutputStream fos = null;
                    try{
                        fos = new FileOutputStream(searchedFile);
                        if(!searchedFile.exists()){
                            searchedFile.createNewFile();
                        }
                        SearchMain.fos = fos;
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                    String keyWordsStr = keyWordsText.getText();
                    String[] keyWordsArr = null;
                    if(keyWordsStr.indexOf(",") > 0){
                        keyWordsArr = keyWordsStr.split(",");
                    }else{
                        keyWordsArr = new String[]{ keyWordsStr }; 
                    }
                    LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
                    ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 100, 3600, TimeUnit.SECONDS, workQueue);
                    for(int i = 0; i < keyWordsArr.length; i++){
                        String keyWords = keyWordsArr[i];
                        ThreadMain threadMain = new ThreadMain(i, searchDirPath, keyWords);
                        executor.execute(threadMain);
                    }
                    if(executor.isTerminated() && SearchMain.fos != null){
                        try {
                            SearchMain.fos.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            });
            panel.add(searchBtn);
            
            //需要手动设置宽度高度(鼠标操作)
            //frame.pack();
            frame.setVisible(true);
        }
        
    }

    这次改了一个很关键的参数.

    之前这里没加编码格式,结果用中文搜索在MyEclipse中可以搜索出来,打成jar包或exe之后搜索不出来.

    原因:

    因为MyEclipse我设置了默认的编码格式是utf-8.

    2015年10月-2016年3月 总计:5个月.
    2016年11月-2017年6月 总计:7个月.
    2017年7月-2018年4月 总计:9个月.
    2018年5月-2018年5月 总计:1个月.
    2018年6月-2018年12月 总计:6个月.
    2019年1月-2019年12月 总计11个月.
    2020年2月-2021年2月 总计13个月.
    所有总计:5+7+9+1+6+11+13=52个月(4年4个月).
    本人认同二元论.我是理想主义者,现实主义者,乐观主义者,有一定的完美主义倾向.不过,一直都是咸鱼(菜鸟),就算有机会,我也不想咸鱼翻身.(并不矛盾,因为具体情况具体分析)
    英语,高等数学,考研,其他知识学习打卡交流QQ群:946556683
  • 相关阅读:
    【积累总结】JS基础日常总结
    【积累总结】CSS日常总结
    【学习】JavaScript单线程与异步
    【学习指南】淘宝首页性能优化实践
    【学习】JS中的跨域
    007_stdc_C语言基础
    006_stdc_C语言基础
    005_stdc_C语言基础
    004_stdc_C语言基础
    003_stdc_linux基本常用命令_C语言基础
  • 原文地址:https://www.cnblogs.com/JimmySeraph/p/9442521.html
Copyright © 2020-2023  润新知