缓冲阅读器字符计数



我对Java和一般的编码相当陌生。在下面的程序中,将此设置为读取文件中的行数和字符数。

虽然它给出了正确的行数,但我得到的字符比我的.txt文件中的字符多,所以我假设它也在读取新的行字符。举个例子,在一个带有文本的测试文件中:"你好world"它将读取字符计数为12而不是10。

关于如何让我的程序只读取字符而不是新的行字符,有什么建议吗?

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;
public class ReadFile 
{
     public static void main(String[] args) 
     {
         try {  /*define block of code to test for errors while it is being executed*/
             String inName = JOptionPane.showInputDialog("Please enter the input file name here");
             int linecount = 0, charcount = 0;
            
             
             /*open the input file*/
             BufferedReader inBuf = new BufferedReader (new FileReader (inName)); /*Initializes buffered reader*/
             
             while ((inBuf.readLine()) !=null) { /*reads the contents of the file, line by line*/
                 linecount++; /*counts the number of lines read*/
             }
             
             inBuf.close(); /*closes input file*/
             
             
             BufferedReader inBuf2 = new BufferedReader (new FileReader (inName));
             while ((inBuf2.read()) != -1) {
                 charcount++; /*counts the number of characters read*/
             }
             
             /*closes input file*/
             inBuf2.close();
             
             /*Displays the number of lines and characters read*/
             JOptionPane.showMessageDialog(null, "Number of lines in this file is: " + linecount);
             JOptionPane.showMessageDialog(null, "Number of characters in this file is: " + charcount);
             
         }
         /*catch that allows code to be executed if error occurs*/
         catch (FileNotFoundException f) {
             JOptionPane.showMessageDialog(null, "File cannot be found! Details:n" + f);
         }
         catch (IOException a) {
             JOptionPane.showMessageDialog(null, "An error has occured when reading this file! Details:n" + a);
         }
         
         System.exit(0); /*exits system*/
     }
}

我在本地运行你的代码。

  1. "你好world"有11个字符。你必须在hello和world之间加入空格。
  2. 我假设你在"world"后面有一个空白。这就是为什么你看到的是12而不是11。
  3. 你可能想重构一下你的代码。特别是不要打开同一个文件两次,因为它效率低下,你应该在try/catch/finally的finally块中关闭BufferedReader,或者对资源使用try。这是为了避免由于没有正确关闭流而导致的潜在内存泄漏,因为可能已经抛出了异常。

如果您只想计数字母或字母数字字符,那么签出java.lang。字符# isLetterOrDigit (char ch)

tldr;这里有一个简单的解决方法。在读取

字符时添加if语句
while (( c= inBuf2.read()) != -1) {
   if(Character.isLetter(c))
   charcount++; /*counts the number of characters read*/
}

最新更新