2018-06-09总结:

ForkJoin确实可以很快速的去解析文件并统计关键词的数量,但是如果文件过大就会出现内存溢出,是否可以通过虚拟内存方式解决内存溢出的问题呢?

package com.oxygen.forkjoin.model;

import java.util.List;
/**
 * 文档
 * @author renguanyu
 *
 */
public class Document {

    private List<String> lines;

    public Document(List<String> lines) {
        super();
        this.lines = lines;
    }

    public List<String> getLines() {
        return lines;
    }

    public void setLines(List<String> lines) {
        this.lines = lines;
    }

}
package com.oxygen.forkjoin.model;

import java.util.List;
/**
 * 文件夹
 * @author renguanyu
 *
 */
public class Folder {

    private List<Folder> subFolders;
    private List<Document> documents;

    public Folder(List<Folder> subFolders, List<Document> documents) {
        this.subFolders = subFolders;
        this.documents = documents;
    }

    public List<Folder> getSubFolders() {
        return subFolders;
    }

    public void setSubFolders(List<Folder> subFolders) {
        this.subFolders = subFolders;
    }

    public List<Document> getDocuments() {
        return documents;
    }

    public void setDocuments(List<Document> documents) {
        this.documents = documents;
    }

}
package com.oxygen.forkjoin.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.oxygen.forkjoin.model.Document;
/**
 * 文档服务
 * @author renguanyu
 *
 */
public class DocumentService {

    /**
     * 读取文件中所以数据
     * @param file 文件
     * @return 文档
     */
    public static Document fromFile(File file) {
        List<String> lines = new ArrayList<>();
        try(BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line = reader.readLine();
            while (line != null) {
                lines.add(line);
                line = reader.readLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Document(lines);
    }

}
package com.oxygen.forkjoin.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

import com.oxygen.forkjoin.model.Document;
import com.oxygen.forkjoin.model.Folder;
import com.oxygen.forkjoin.task.FolderSearchTask;
/**
 * 文件夹服务
 * @author renguanyu
 *
 */
public class FolderService{

    /**
     * 递归查询文件夹中所有的数据
     * 1.在内存中建立文件夹的结构
     * 2.把数据都加载到这个结构中,方便下一步计算
     * @param dir 文件夹
     * @return 文件夹
     */
    public static Folder fromDirectory(File dir) {
        List<Document> documents = new ArrayList<>();
        List<Folder> subFolders = new ArrayList<>();
        for (File entry : dir.listFiles()) {
            if (entry.isDirectory()) {
                subFolders.add(FolderService.fromDirectory(entry));
            } else {
                documents.add(DocumentService.fromFile(entry));
            }
        }
        return new Folder(subFolders, documents);
    }

    /**
     * 获取关键词总数
     * @param targetFolder 目标文件夹
     * @param keyword 关键词
     * @throws IOException
     */
    public static long getKeywordTotal(String targetFolder, String keyword) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        //把文件夹中的数据加载到内存中,我这个文件夹中就一个日志文件
        File dir = new File(targetFolder);
        Folder folder = FolderService.fromDirectory(dir);
        //创建一个搜索任务
        FolderSearchTask task = new FolderSearchTask(folder, keyword);
        //开始执行fork/join任务
        long counts = forkJoinPool.invoke(task);
        return counts;
    }

}
package com.oxygen.forkjoin.task;
import java.util.List;
import java.util.concurrent.RecursiveTask;

import com.oxygen.forkjoin.model.Document;
/**
 * 文档搜索任务
 * @author renguanyu
 *
 */
public class DocumentSearchTask extends RecursiveTask<Long> {

    private static final long serialVersionUID = 1L;

    private Document document;
    private String searchedWord;

    public DocumentSearchTask(Document document, String searchedWord) {
        super();
        this.document = document;
        this.searchedWord = searchedWord;
    }

    @Override
    protected Long compute() {
        long count = 0;
        List<String> lines = document.getLines();
        for (String line : lines) {
            String[] words = line.trim().split("(\\s|\\p{Punct})+");
            for (String word : words) {
                if (searchedWord.equals(word)) {
                    count = count + 1;
                }
            }
        }
        return count;
    }

}
package com.oxygen.forkjoin.task;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

import com.oxygen.forkjoin.model.Document;
import com.oxygen.forkjoin.model.Folder;
/**
 * 文件夹搜索任务
 * @author renguanyu
 *
 */
public class FolderSearchTask extends RecursiveTask<Long> {

    private static final long serialVersionUID = 1L;

    private Folder folder;
    private String searchedWord;

    public FolderSearchTask(Folder folder, String searchedWord) {
        super();
        this.folder = folder;
        this.searchedWord = searchedWord;
    }
    //计算方法
    @Override
    protected Long compute() {
        long count = 0L;
        List<RecursiveTask<Long>> forks = new ArrayList<>();
        //获取文件夹下的子文件夹
        for (Folder subFolder : folder.getSubFolders()) {
            //递归文件夹搜索任务
            FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
            //把任务添加到分叉列表,用于合并任务
            forks.add(task);
            //放到工作队列中
            task.fork();
        }
        //获取文件夹下的文档
        for (Document document : folder.getDocuments()) {

            DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
            //把任务添加到分叉列表,用于合并任务
            forks.add(task);
            //放到工作队列中
            task.fork();
        }
        //合并工作队列中各个线程计算结果的值
        for (RecursiveTask<Long> task : forks) {
            count = count + task.join();
        }
        return count;
    }
}
package com.oxygen.forkjoin.test;

import java.io.IOException;
import com.oxygen.forkjoin.service.FolderService;
/**
 * 测试程序
 * @author renguanyu
 *
 */
public class MainTest {

    public static void main(String[] args) throws IOException {

        long startTime = System.currentTimeMillis();

        long counts = FolderService.getKeywordTotal("C:\\test\\logs\\", "null");

        long stopTime = System.currentTimeMillis();

        long completeTime = stopTime - startTime;

        System.out.println(counts + " , fork / join search took " + completeTime + "ms");
    }
}

ForkJoin统计文件夹中包含关键词的数量的更多相关文章

  1. Path,Files巩固,题目:从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中

    这个题目用传统的File,InputStream可以做,但是如果用Files,Path类做,虽然思路上会困难一些,但是代码简洁了很多,以下是代码: import java.io.IOException ...

  2. 使用.NET统计文件夹中文件总数

    软件下载: http://hovertree.com/h/bjaf/hwqtjwjs.htm 截图: 使用方法:点击按钮,选择文件夹,就可以显示文件夹中包含的文件总数. 这个项目包含在HoverTre ...

  3. 【linux】统计文件夹中文件行数

    统计当前目录下,排除venv目录,剩余所有py文件的行数 wc -l `find -path ./venv -prune -o -name '*py'`

  4. java基础 File 递归删除文件夹中所有文件文件夹 目录(包含子目录)下的.java文件复制到e:/abc文件夹中, 并统计java文件的个数

    File 递归删除文件夹中所有文件文件夹 package com.swift.kuozhan; import java.io.File; import java.util.Scanner; /*键盘录 ...

  5. 用字符流实现每个文件夹中创建包含所有文件信息的readme.txt

    package com.readme; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; i ...

  6. 用C语言实现统计一个文件夹中各种文件的比例

    <UNIX环境高级编程>中的程序清单4-7就介绍了如何实现递归地统计某个目录下面的文件!我刚开始看过它的代码后,觉得照着敲太没意思了,所以就合上书自己写了一遍!为此还写了一篇博文,这是博文 ...

  7. (文档)Shader.Find (在编译时,只包含那些使用中的shader或位置在"Resources"文件夹中shader)

    Shader.Find 查找 static function Find (name : string) : Shader Description描述 Finds a shader with the g ...

  8. 【原】Mac下统计任意文件夹中代码行数的工

    [链接][原]Mac下统计任意文件夹中代码行数的工http://www.cnblogs.com/wengzilin/p/4580646.html

  9. .net网站上传图片换电脑不显示 当不用网站的IP地址访问图片,只用相对路径访问时,在发布网站的时候,将上传图片的目标文件夹,包含在项目中再发布即可。

    .net网站上传图片换电脑不显示 当不用网站的IP地址访问图片,只用相对路径访问时,在发布网站的时候,将上传图片的目标文件夹,包含在项目中再发布即可.

随机推荐

  1. H3C 环路避免机制四:定义最大值

  2. 2018-2-13-win10-UWP-ListView-模仿开始菜单

    title author date CreateTime categories win10 UWP ListView 模仿开始菜单 lindexi 2018-2-13 17:23:3 +0800 20 ...

  3. C# 在基类定义好方法让子类继承接口就能实现

    在 C# 里面,接口的定义只需要类里面存在和接口声明相同的方法或属性就可以,而存在的方法或属性是在子类定义的还是基类里面定义的都无所谓.也就是在基类里面写好了方法,但不继承接口,等子类继承接口的时候就 ...

  4. 1134 最长上升子序列 (序列型 DP)

    思路: 由于一般的动态规划时间复杂度是O(n^2)(哈哈哈哈 第一次用的就是这个!)用在这里由于n最大为50000 所以会超时 到这里我们可以用一个数组来动态维护这个最长上升的子序列,将你要输入的子序 ...

  5. Linux 内核 启动时间

    为见到 PCI 如何工作的, 我们从系统启动开始, 因为那是设备被配置的时候. 当一个 PCI 设备上电时, 硬件保持非激活. 换句话说, 设备只响应配置交易. 在上电时, 设备没有内存并且没有 I/ ...

  6. Stylized Image Caption论文笔记

    Neural Storyteller (Krios et al. 2015) : NST breaks down the task into two steps, which first genera ...

  7. 如何使用IoTSharp对接ModBus?

    提到对接ModBus 那么或许大家最熟悉的可能是 HslCommunication 和SharpSCADA 了,是GitHub 上关注最多的此类开源项目,  因此IoTSharp将通过HSL组件进行数 ...

  8. Hadoop Authentication

    我被被派去做别的事情了,所以与hadoop相关的工作就只能搁下.写篇总结,把最近遇到的和kerberos相关的东西列一下. JAAS是Java 认证和授权服务(Java Authentication ...

  9. VC/c++版本获取现行时间戳精确到毫秒

    时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数.通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完 ...

  10. 从头学pytorch(十二):模型保存和加载

    模型读取和存储 总结下来,就是几个函数 torch.load()/torch.save() 通过python的pickle完成序列化与反序列化.完成内存<-->磁盘转换. Module.s ...