从文件中删除多余的空格

时间:2015-10-01 15:18:13

标签: java

我正在尝试使用此代码,但它似乎无法正常工作。

我已经初始化了字符串,但是因为没有初始化它而收到错误。

而不是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();    
    }
}

1 个答案:

答案 0 :(得分: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();
    }
}

你不需要带字符串的东西。对于空格,我添加了一个布尔变量来检查我们是否已经有空格。 我希望它有所帮助。

相关问题