zoukankan      html  css  js  c++  java
  • Java 多线程查找文件中的内容

    学过了操作系统,突然不知道多线程有什么用了。

    看了一下百度,发现多线程,可以提升系统利用率

    在系统进行IO操作的时候,CPU可以处理一些其他的东西,等IO读取到内存后,CPU再处理之前的操作。

    总之可以在用户层面,可以提升效率,不过,有时候多线程设计不当,调试也很麻烦

    今天尝试一下简单的查找文件后缀以txt 里的内容 demo

    SeachFileContent类,用来查询文件内容

    package thread;
    
    import java.io.File;
    import java.io.IOException;
    
    public class SeachFileContent {
    
        public static void main(String[] args) {
            File file = new File("D://TT//Draymonder");
            if(!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                String content="复制";
                searchFileContent(file,content);
            }
        }
    
        public static void searchFileContent(File file, String content) {
            if(file.isFile()) {
                if(file.getName().toLowerCase().endsWith(".txt")) {
                    new SearchFileThread(file, content).start();
                }
            }
            if(file.isDirectory()) {
                File[] files = file.listFiles();
                for(File singlefile : files) {
                    searchFileContent(singlefile, content);
                }
            }
        }
    }

    SearchFileThread类,用来多线程处理文件内容的查询

    package thread;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class SearchFileThread extends Thread {
        private File file;
        private String content;
        SearchFileThread() {}
        
        SearchFileThread(File file, String content) {
            this.file = file;
            this.content = content;
        }
        
        private String getFileContent(File file) {
            try(FileReader fileReader = new FileReader(file)) {
                char []all = new char[(int)file.length()];
                fileReader.read(all);
                return new String(all);
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }
    @Override
    public void run() { String str = getFileContent(this.file); if(null != str) { if(str.contains(this.content)) { System.out.printf("在%s中含有 目标串"%s" ...%n",this.file.getName(),this.content); } } } }
  • 相关阅读:
    连分数法解佩尔方程特解
    hdu2281&&POJ1320——Pell方程
    Gym
    代入法求递推式
    nodemcu固件的烧录及lua开发
    ESP8266MOD、刷可以使用AT指令的固件、作为客户端向贝壳云端发送固定数据
    Quick Start NodeMCU / ESP8266 12E
    CF388C&&2018EC Final D题——博弈&&水题
    使用cookie登录网盘账号
    Spring的Bean之Bean的基本概念
  • 原文地址:https://www.cnblogs.com/Draymonder/p/9565110.html
Copyright © 2011-2022 走看看