0

I have made this program to count the number of characters excluding space in a file. But when I test it on inputs which are of more than a line then, it starts giving error. Though, I know that for every line that I add to the file, error increases by +2. But why is this happening?

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");
        }

    }
}

2 Answers2

0

You are counting the end-of-line characters, which in Linux/UNIX would be an ASCII line-feed and for Windows/MSDOS would be line-feed and carriage return.

Note that the file could also contain other whitespace characters, such as tab, form feed, etc. How should those be counted?

For more info, see https://stackoverflow.com/a/4510327/1532454

Jeff Learman
  • 2,914
  • 1
  • 22
  • 31
0

When you read char, you get also carriage return (CR, \r) and new line (LF, \n). You should consider it in condition.

Replace this:

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

With this:

char readChar = (char)i;
if(!(readChar==(' ') || readChar==('\r') || readChar==('\n')))
mkczyk
  • 2,460
  • 2
  • 25
  • 40