我必须计算文本文件中的字符数。 我想用for循环来做,但是,我不知道如何引用文件的长度?
public void countLetters(String) {
for (int i = 0; i < ; i++) {
}
}
我应该在i <
之后写些什么?
答案 0 :(得分:2)
您首先需要阅读该文件的内容。你可以用以下方式完成。
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
其中file是文件对象,即在您的情况下,您要读取的文本文件。然后读取文件的每一行,如下
String temp;
int totalNoOfCharacters = 0;
int noOfLines = 0; //To count no of lines IF you need it
while ( (temp = br.readline()) != null ){
noOfLines++;
totalNoOfCharacters += temp.length(); //Rememeber this doesnot count the line termination character. So if you want to consider newLine as a character, add one in this step.
}
答案 1 :(得分:0)
FileReader fr = new FileReader("pathtofile");
BufferedReader br = new BufferedReader(fr);
String line = "";
int cont=0;
while ((line = br.readLine()) != null) {
line = line.split("\\s+").trim();
cont+=line.length();
}
不要忘记关闭流并使用try catch。
答案 2 :(得分:0)
最好先阅读 while 循环中的每个字符,然后首先检查文件的结尾,而不是尝试使用 for 循环。 e.g。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
. . . .
. . . .
try
{
BufferedReader reader = new BufferedReader(new FileReader("myFile.txt"));
String textLine = reader.readLine();
int count = 0;
while (textLine != null)
{
textLine.replaceAll("\\s+",""); // To avoid counting spaces
count+= textLine.length();
textLine = reader.readLine();
}
reader.close();
System.out.println("Number of characters in myFile.txt is: " + count);
}
catch(FileNotFoundException e)
{
System.out.println("The file, myFile.txt, was not found");
}
catch(IOException e)
{
System.out.println("Read of myFile.txt failed.");
e.printStackTrace();
}
答案 3 :(得分:-1)
Scanner scanner = new Scanner(yourfile);
while(scanner.hasNext()){
word = scanner.next();
char += word.length();
}