私はテキストファイルの文字を数えなければなりません。 私はforループでやりたいのですが、ファイルの長さを参照する方法がわかりません。javaのテキストファイルをどのように参照すればよいですか?
public void countLetters(String) {
for (int i = 0; i < ; i++) {
}
}
i <
の後に何を書きますか?
私はテキストファイルの文字を数えなければなりません。 私はforループでやりたいのですが、ファイルの長さを参照する方法がわかりません。javaのテキストファイルをどのように参照すればよいですか?
public void countLetters(String) {
for (int i = 0; i < ; i++) {
}
}
i <
の後に何を書きますか?
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();
}
は、ストリームを閉じて、トライキャッチを使用することを忘れないでください。
まず、ファイルの内容を読む必要があります。あなたは次のようにすることができます。
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
ここで、fileはファイルオブジェクト、つまり読みたいテキストファイルです。そして、 whileループ内の各各文字を読むためにこの
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.
}
Scanner scanner = new Scanner(yourfile);
while(scanner.hasNext()){
word = scanner.next();
char += word.length();
}
コードを説明するためにテキストを追加する必要があります –
より良いように、ファイルの各行を読んでその用を使用しようとするよりも、ファイルの終わりのための最初のチェックループ。例:
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();
}
さて、ファイルから*情報をどのように読み取っていますか?このループの中で何をしていますか? – David