[Solved] Java Code removing new line


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).

solved Java Code removing new line