笔试题--对一个编码格式为utf-8,文件后缀为txt的文本文件,要求使用JAVA的NIO方法,对文件中特定单词出现次数进行统计,输出对应单词的出现次数

 

1.题目:
对一个编码格式为utf-8,文件后缀为txt的文本文件,要求使用JAVA的NIO方法,对文件中特定单词出现次数进行统计,输出对应单词的出现次数。
要求:
1. 输入一个本地文本文件地址,文本文件最大为2G,文本编码类型为utf-8。
2. 使用JAVA提供的NIO方法进行文本统计。
3. 控制程序运营时对内存空间的占用,在JVM参数为-Xmx20M 的情况下可以正常运行,并统计特定单词出现次数和总时间耗时。
4. 出于对效率的考虑,可以采用多线程并行分析的方式。

 

public class ReadFileNioThread implements Runnable {

    public String filePath = "D:\\file.txt";  //文件路径
    public String keyword = "abc";  //关键字
    public int bufSize = 10000; //设置缓冲区大小

    public static void main(String args[]) throws Exception {
        ReadFileNioThread readThread = new ReadFileNioThread();
        new Thread(readThread, "读取文件线程").start();
    }

    @Override
    public void run() {
        long startTime = System.currentTimeMillis();
        FileChannel fileChannel = null;
        try {
            //如果关键字比分配的内存大则直接返回
            if (keyword.length() > 20 * 1024 * 1024) {
         return; }
else { //如果关键字比缓冲区大则设置关键字长度加1位缓冲区大小 if (keyword.length() > bufSize) { bufSize = keyword.length() + 1; } } int num = 0; String joint = ""; File file = new File(filePath); fileChannel = new RandomAccessFile(file, "r").getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize); while (fileChannel.read(byteBuffer) != -1) { int readSize = byteBuffer.position(); byte[] bs = new byte[readSize]; byteBuffer.rewind(); byteBuffer.get(bs); String line = new String(bs, 0, bs.length, "UTF-8"); line = joint + line; while (line.length() > keyword.length()) { int index = line.indexOf(keyword); if (index > -1) { num++; line = line.substring(index + keyword.length()); //将截取到最后的部分取出来,拼接到下一次从缓冲区取出的字符串前,避免关键字截断 if (line.length() <= readSize) { joint = line; } } else { break; } } byteBuffer.clear(); } if (fileChannel.isOpen()) { fileChannel.close(); } long endTime = System.currentTimeMillis(); System.out.println("关键字数量为:" + num + "------计算耗时" + (endTime - startTime) + "毫秒"); } catch (IOException e) { if (fileChannel.isOpen()) { try { fileChannel.close(); } catch (IOException es) { System.out.println("关闭出现异常"); } } System.out.println("文件读取出现异常"); } finally { if (fileChannel.isOpen()) { try { fileChannel.close(); } catch (IOException e) { System.out.println("关闭出现异常"); } } } } }
posted @ 2020-01-21 11:20  大浪不惊涛  阅读(437)  评论(0编辑  收藏  举报