简体   繁体   中英

Java Code removing new line

I am writing a java code to remove extra spaces from a text file passed by command line argument. This code runs successfully but it is also removing \\n from every line. Can someone give me the reason why this is happening and a solution for this problem?

Here is the code

import java.io.*;

//remove extra spaces from a file

class q3
{
    public static void main(String args[]) throws IOException
    {
        File ff=new File(args[0]);
        if(!ff.exists())
        {
            System.out.println("Source file not found");
            System.exit(0);
        }

        File t=new File("temp.txt");
        t.createNewFile();

        FileInputStream fis=new FileInputStream(ff);
        FileOutputStream fos=new FileOutputStream(t);

      int ch,spaces=0,nn=0;

      while((ch=fis.read())!=-1)
      {
          if(ch=='\n')
              nn++;

          if(Character.isWhitespace(ch))
          {
              spaces++;
          }
          else{
             if(spaces>=1)
            { spaces=0;
                fos.write(' ');
                fos.write(ch);}
            else {  fos.write(ch) ;  }
        }
      }

      fis.close();
      fos.close();

        ff.delete();

        if(t.renameTo(ff))
            System.out.println("Program Execution Successful, having "+(1+nn)+ " lines");

    }

}

The lines

if(Character.isWhitespace(ch))
{
    spaces++;
}
else{
if(spaces>=1)
{ spaces=0;
fos.write(' ');
fos.write(ch);}

in your code ensures you condense all whitespace characters into a single space. A newline is considered a whitespace character so you skip those as well.

If you don't want to group the newline with the other whitespace in this case a quick fix would be to modify the line

if(Character.isWhitespace(ch))

to

if(Character.isWhitespace(ch) && ch != '\n')

A better way would be to read in your input line-for-line and write them out line-by-line as well. You could use (for example) http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#readLine-- and http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#newLine() (after writing the line out). This way your implementation is not dependent upon system-specific line separators (ie, other systems could have different characters to end a line with instead of \\n ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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