简体   繁体   English

我应该如何引用java中的文本文件?

[英]How should I refer to a text file in java?

I have to count the characters in a text file.我必须计算文本文件中的字符数。 I would like to do it with a for loop, however, I do not know how to refer to the length of the file?我想用for循环来做,但是,我不知道如何引用文件的长度?

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

    }
}

What should I write after the i < ?i <之后i <应该写什么?

Well you first need to read the contents of the file.那么你首先需要读取文件的内容。 You can do it the following manner.您可以通过以下方式进行。

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

Where file is the file object ie in your case, the text file which you want to read.其中 file 是文件对象,即在您的情况下,您要阅读的文本文件。 Then read each line of the file, like this然后读取文件的每一行,像这样

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

Don't forget to close streams and use try catch .不要忘记关闭流并使用 try catch 。

Maybe better to read each each character within a while loop that first checks for the end of the file than to try using a for loop.在首先检查文件末尾的while循环中读取每个字符可能比尝试使用for循环更好。 eg例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM