I would suggest using the read() method which returns one int at a time is very inefficient. Learn to use a Buffered reader, which you will find about in the Java Tutorials. Don’t use input streams for text files; use readers instead. The buffered reader has methods which return a whole line as a String, which will match the length of the line exactly. No need to mess around with arrays 9999 long in the hope of having enough space (what happens when you have a 10000 character file ?).
When you have the String, you can consider its replaceAll method. Or you can put the String into a StringBuilder and iterate it looking for double spaces. There are methods in the Character class which tell you whether a particular character is whitespace.
naresh vyas wrote:I want to remove extra spaces from a file like: "hi___how___are____you?" get converted into "hi how are you?".
Are you sure? Presumably the person/program that put those extra spaces in there had some reason for it, and by replacing them you may have just destroyed it for any program that does use those extra spaces.
A non-destructive alternative is to use a "view". Assuming you've taken Campbell's excellent advice, and are reading the File line by line, you could write a very simple method:and have your program use that whenever it needs to look at a "line"
That way, you don't have to replace the contents of your File - which, in itself, is probably a fairly slow operation.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
subject: to remove extra spaces from a file using streams and file class