2016-09-11 5 views
1

私はテキストファイルの文字数を数えようとしています。しかし、行の最後には\ r \ nではなく、文字と空白だけを数えることができます。どのように含めることができますか? 以下の関数は、ファイル内の行数、単語数、および文字数をカウントします。行末を含むDOSテキストファイルの文字をカウントするには?

public static void Count(String FILENAME, int n) throws IOException { 
    inFile = new BufferedReader(new FileReader(FILENAME)); 
    String currentLine; //= inFile.readLine(); 
    while ((currentLine=inFile.readLine()) != null) { 
     lines[n]++; 
     bytes[n]+=currentLine.length(); 
     bytes[n]++; 
     String[] WORDS = currentLine.split(" "); // split the string into sub-string by whitespace 
     // to separate each words and store them into an array 
     words[n] = words[n] + WORDS.length; 
     if (currentLine.length()==0) 
      words[n]--; 

    } 

} 

答えて

0

\ r \ n read()メソッドを使用してください。

readLine()メソッドテキストの行を読み取ります。行は、改行( '\ n')、復帰( '\ r')、改行の直後に続く改行のいずれかで終了すると見なされます。

戻り値: 行の終了文字が含まれていない行の内容を含む文字列。ストリームの終わりに達した場合はnull。

+0

がなく(読み取り)整数を返し、Iは、文字列が必要です行を単語に分割する –

1

簡単な方法の1つは、文字ストリームはreadLine()を呼び出すたびに1文字を与えるため、ライン指向のストリームの代わりに文字ストリームを使用することです。

public static void Count(String FILENAME, int n) throws IOException { 
 
    inFile = new FileReader(FILENAME); 
 
    char currentCharacter; 
 
    int numCharacters = 0; 
 

 
    String currentLine = ""; 
 
    while ((currentCharacter=inFile.readLine()) != null){ 
 
     if(currentCharacter == '\n') 
 
     { 
 
     lines[n]++; 
 
     bytes[n]+=currentLine.length(); 
 
     bytes[n]++; 
 
     String[] WORDS = currentLine.split(" "); 
 
     words[n] = words[n] + WORDS.length; 
 
     if (currentLine.length()==0) 
 
      words[n]--; 
 
     } 
 
     currentCharacter=inFile.readLine(); 
 
     currentLine += currentCharacter; 
 
     numCharacters ++; 
 
    }

そして合計はnumCharactersに格納されます。行数やバイト数などをカウントする機能を保持するには、ループの前にString行を宣言し、各文字をループの末尾に連結することができます。いったん\ nを押すと、line変数に1つの行があることがわかります。その後、Uは、いずれかによって行[n]をインクリメントすることができた(line.lengthによって[n]はバイトを増加させる)、などの情報の

源:https://docs.oracle.com/javase/tutorial/essential/io/charstreams.html

関連する問題