欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java HashSet对txt文本内容去重(统计小说用过的字或字数)

程序员文章站 2023-11-13 11:41:34
Java HashSet对txt文本内容去重(统计小说用过的字或字数) 基本思路: 1、字节流读需要去重的txt文本。(展示demo为当前workspace下名为utf 8.txt的文本) 2、对读取到的单个字节判断 (1)如果为字母或特殊字符。操作(2) (2)添加到HashSet中,如果 Has ......

java hashset对txt文本内容去重(统计小说用过的字或字数)

基本思路:

1、字节流读需要去重的txt文本。(展示demo为当前workspace下名为utf-8.txt的文本)

2、对读取到的单个字节判断
(1)如果为字母或特殊字符。操作(2)
(2)添加到hashset中,如果hashset.add()返回true代表该字符添加到hashset失败,即字符未出现过,故对其做写操作。(展示demo写到的是当前workspace下的u.txt)
(3)如果为中文字符,根据txt文本编码取对应字节数(如:utf-8编码三个字节,gbk编码两个字节,展示demo为utf-8编码的txt文本),操作(2)
尤其注意文本编码格式

3、关闭流

如需统计字数即两个hashset的长度相加即可,本文未写出。

展示demo

        fileinputstream fileinputstream = new fileinputstream("utf8.txt");
        fileoutputstream fileoutputstream=new fileoutputstream("u.txt");
        int len = 0;
        hashset<integer> c = new hashset<>();
        hashset<string> z = new hashset<>();
        while ((len = fileinputstream.read()) != -1) {
            if (1 <= len && len <= 127) {//ascii码值判断是否为字母或特殊字符
                if (c.add(len)){
                    //system.out.printf(string.valueof((char) len));
                    fileoutputstream.write(len);
                }
            } else {
                int first = len;
                int second = fileinputstream.read();
                int third = fileinputstream.read();
                //一个字符对应三个字节
                byte[] bytes = {(byte) first, (byte) second, (byte) third};
                if ( z.add(bytes)){
                    //system.out.print(new string(bytes));
                    fileoutputstream.write(bytes);
                }
            }
        }

仅提供思路,写法不一定是最好的。
有问题请私聊我。