简体   繁体   English

Java代码删除新行

[英]Java Code removing new line

I am writing a java code to remove extra spaces from a text file passed by command line argument.我正在编写一个 java 代码来从命令行参数传递的文本文件中删除多余的空格。 This code runs successfully but it is also removing \\n from every line.此代码成功运行,但它也从每一行中删除了\\n 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).您可以使用(例如) http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#readLine--http://docs.oracle.com/javase/7 /docs/api/java/io/BufferedWriter.html#newLine() (写出该行之后)。 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 ).通过这种方式,您的实现不依赖于系统特定的行分隔符(即,其他系统可能有不同的字符来结束一行而不是\\n )。

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

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