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

huangapple go评论70阅读模式
英文:

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 一样。
感谢所有的回答。

英文:

i'd like to know whether there is an easy way to count the letters in a txt file.
Lets say i have different txt files with a different amount of letters written in it, and i want to delete all txt files which have more letters than lets say 2000.
Furthermore let's assume i deal with one txt at a time. I've tried this so far:

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();
		}

Is there an easier way or one which has better performance?
Reading all letters in a String to just discard them afterwards seems like a lot of timewaste.
Should i maybe use an InputStream and use available() and then divide? On the other hand i saw that available() counts literally everything like when i press Enter in the txt file it adds +2 to the amount of letters.
Thanks for all answers.

答案1

得分: 1

你可以像下面这样使用Files.lines


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

英文:

You can use Files.lines as below,

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

huangapple
  • 本文由 发表于 2020年5月4日 16:43:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/61588275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定