使用 read() 从 FileInputStream 读取字符

Reading the characters from FileInputStream using read()

我制作了这个程序来计算文件中不包括 space 的字符数。但是当我在超过一行的输入上测试它时,它开始出错。虽然,我知道对于我添加到文件中的每一行,错误都会增加 +2。但为什么会这样?

import java.lang.*;
import java.util.*;
import java.io.*;
public class fileread_1
{
    public static void main (String args[]) throws IOException
    {
        try{
            FileInputStream fs = new FileInputStream("checkerx.txt");
            FileOutputStream f_out = new FileOutputStream("check_twice.txt",false);
            PrintStream ps = new PrintStream(f_out);
            int i=0,count =0;
            while((i=fs.read())!=-(1)){
            if(!(((char)i)==(' ')))
                count = count +1;
            ps.print((char)i);
            }
            System.out.println(count);
        }
        catch(FileNotFoundException e)
        {
            System.out.println("the file was not found");
        }

    }
}

您计算的是行尾字符,在 Linux/UNIX 中是 ASCII 换行符,在 Windows/MSDOS 中是换行符和回车符 return。

请注意,该文件还可能包含其他空白字符,例如制表符、换页符等。这些应该如何计算?

有关详细信息,请参阅

当您读取 char 时,您还会得到回车符 return(CR,\r)和换行符(LF,\n)。你应该考虑它的状况。

替换为:

if(!(((char)i)==(' ')))

有了这个:

char readChar = (char)i;
if(!(readChar==(' ') || readChar==('\r') || readChar==('\n')))