2015-10-01 61 views
-1

我在尝试此代码,但它似乎不起作用。从文件中删除多余的空格

我已经初始化了字符串,但是没有初始化它。

而不是replaceAll(),任何其他有效的方法()或代码将不胜感激。谢谢!

import java.io.*; 
class Rspace 
{ 
    public static void main(String args[]) throws IOException 
    { 
     int arr[] = new int[3]; 
     if(arr.length<2) 
      { 
       System.out.print("Parameters are missing"); 
       System.exit(0); 
      } 
     if(arr.length>2) 
      { 
       System.out.print("No. of parameters are exceeded"); 
       System.exit(1); 
      } 
     File f = new File(args[0]); 
     if(!f.exists()) 
      { 
       System.out.print("File does not exists"); 
       System.exit(2); 
      } 
     FileInputStream fis = new FileInputStream(args[0]); 
     FileOutputStream fos = new FileOutputStream(args[1]); 
     int ch; 
     String str; 
     while((ch=fis.read())!=-1) //Reading character & returning ASCII value;shifting to next character 
      { 
       fos.write(ch); 
       str.replaceAll("\\s",""); //Removes all WhiteSpaces 
      } 
      fis.close(); 
      fos.close();  
    } 
} 
+0

当你调用'replaceAll'时,你认为'str'有什么价值?你为什么这么认为? –

+3

这甚至不是问题。 'str''永远不会被赋值,它保持单位。 – f1sh

+3

你正在读单个字符,然后突然处理字符串。 – ergonaut

回答

0

如果你想摆脱空格的,那么你可以这样做的:

import java.io.*; 

class Rspace { 
    public static void main(String args[]) throws IOException { 
     int arr[] = new int[3]; 
     if (arr.length < 2) { 
      System.out.print("Parameters are missing"); 
      System.exit(0); 
     } 
     if (arr.length > 2) { 
      System.out.print("No. of parameters are exceeded"); 
      System.exit(1); 
     } 
     File f = new File(args[0]); 
     if (!f.exists()) { 
      System.out.print("File does not exists"); 
      System.exit(2); 
     } 
     FileInputStream fis = new FileInputStream(args[0]); 
     FileOutputStream fos = new FileOutputStream(args[1]); 
     int ch; 
     boolean lastSpace = false; 
     while ((ch = fis.read()) != -1) // Reading character & returning ASCII 
             // value;shifting to next character 
     { 
      if (!Character.isWhitespace(ch)) { 
       fos.write(ch); 
       lastSpace = false; 

      } else if (!lastSpace) { 
       fos.write(ch); 
       lastSpace = true; 
      } 
     } 
     fis.close(); 
     fos.close(); 
    } 
} 

你不需要用绳子的东西。对于空格,我添加了一个布尔变量来检查我们是否有空间。 我希望它有帮助。