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); } } } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM