如何计算写入txt文件的字母数量

How to calculate the amount of letters written in a txt file

我想知道是否有一种简单的方法来计算 txt 文件中的字母。 假设我有不同的 txt 文件,其中写入了不同数量的字母,我想删除所有字母超过 2000 个的 txt 文件。 此外,假设我一次处理一个 txt。到目前为止我已经试过了:

FileReader reader2 = new FileReader("C:\Users\Internet\eclipse-workspace\test2.txt");
BufferedReader buff = new BufferedReader(reader2)){

int counter = 0;

            while(buff.ready()){
                String aa = buff.readLine();
                counter = counter + aa.length();

            }
            System.out.println(counter);
        }
        catch(Exception e) {
            e.printStackTrace();
        }

是否有更简单的方法或性能更好的方法? 读取一个字符串中的所有字母然后丢弃它们似乎很浪费时间。 我应该使用 InputStream 并使用 available() 然后除法吗?另一方面,我看到 available() 几乎可以计算所有内容,就像我在 txt 文件中按 Enter 键时,它会将 +2 添加到字母数量中。 感谢大家的回答。

您可以使用 Files.lines 如下,

counter = Files.lines(Paths.get("C:\Users\Internet\eclipse-workspace\test2.txt"))
        .mapToInt(String::length)
        .sum();