2017-10-16 65 views
-3

我必須計算文本文件中的字符。 我想用for循環做,但是,我不知道如何引用文件的長度?我應該如何在java中引用一個文本文件?

public void countLetters(String) { 
    for (int i = 0; i <  ; i++) { 

    } 
} 

我應該在i <之後寫什麼?

+1

那麼,你如何*從文件中讀取信息?你在這個循環裏面做什麼? – David

回答

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

那麼你首先需要閱讀文件的內容。你可以按照下面的方式做。

FileReader fr = new FileReader(file); 
BufferedReader br = new BufferedReader(fr); 

其中文件是文件對象,即在你的情況下,你想要讀取的文本文件。然後讀取文件中的每一行,像這樣

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
Scanner scanner = new Scanner(yourfile); 
    while(scanner.hasNext()){ 
     word = scanner.next(); 
     char += word.length(); 
    } 
+2

你需要添加一些文字來解釋你的代碼 –

0

也許更好的循環中讀取每個每個字符,對於文件的末尾比使用嘗試首先檢查循環。 例如

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(); 
} 
相關問題