Java 多線程尋找檔案中的內容

來源:互聯網
上載者:User

標籤:目標   err   []   color   其他   讀取   todo   複製   dex   

學過了作業系統,突然不知道多線程有什麼用了。

看了一下百度,發現多線程,可以提升系統利用率

在系統進行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); } } }}

 

Java 多線程尋找檔案中的內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.