Reputation: 47
I am trying to format a text file. I want to delete all the new line characters except the ones that are used to start a new alinea. By that I mean if the line in the text file is whitespace I want to keep it but all the other newlines need to be deleted.
here is what I have so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Formatting {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("give file name: ");
String filename = in.next();
File inputfile = new File(filename);
Scanner reader = new Scanner(inputfile);
String newline = System.getProperty("line.separator");
PrintWriter out = new PrintWriter("NEW " + filename);
while(reader.hasNextLine()) {
String line = reader.nextLine();
if (line.length() > 2 && line.contains(newline)) {
String replaced = line.substring(0,line.length()) + ' ';
out.print(replaced);
}
else {
out.print(line + ' ');
}
}
in.close();
out.close();
}
}
however now my first if statement never gets executed. Every newline just gets deleted.
Can anybody help me here? It would be very much appreciated.
Upvotes: 0
Views: 302
Reputation: 133
This may help you , read comments to get idea what is the use of each line .
// 3. compress multiple newlines to single newlines
line = line.replaceAll("[\\n]+", "\n");
// 1. compress all non-newline whitespaces to single space
line = line.replaceAll("[\\s&&[^\\n]]+", " ");
// 2. remove spaces from begining or end of lines
line = line.replaceAll("(?m)^\\s|\\s$", "");
Upvotes: 1