Using Buffered Reader and Writer to remove blank lines in a textfile; however I always leave the last line blank

StackOverflow https://stackoverflow.com/questions/23570300

Question

I have a BufferedReaderand BufferedRriter that reads and removes blank lines from a textfile. It all works fine except I cannot for the life of me find a good solution to end it.

 public static void cleanUpData(){
         File inputFile = new File("C:\\Users\\student\\workspace\\EmployeePunch\\src\\EmployeeData.txt");   // Your file  
File tempFile = new File("C:\\Users\\student\\workspace\\EmployeePunch\\src\\EmployeeDataNew.txt");// temp file
BufferedReader reader = null;
BufferedWriter writer = null;
try{
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(tempFile,true));
String currentLine;

while((currentLine = reader.readLine()) != null) {
    if(currentLine.equals("")) continue;
    writer.append(currentLine+"\n");
}
    }
    catch (IOException e) {
        e.printStackTrace();
        }finally{
            try {

                reader.close();
                inputFile.delete();
                writer.close();
                boolean successful = tempFile.renameTo(inputFile);
                System.out.println(successful);
                validateEmployee();
            } catch (IOException ex) {
               ex.printStackTrace();
            }

        }
    }

I know the reason it is doing it is being of the writer.append(currentLine+"\n"); but what would be another solution to stop at the last line?

Is there a way to know when I am right before the last line so to avoid using the +"\n"?

Was it helpful?

Solution

Don't add a newline after every output line. Instead, insert a a newLine before every line after the first line.

For example, you can replace your while loop with the following code:

boolean needsNewLine = false;
while((currentLine = reader.readLine()) != null) {
    if(currentLine.equals("")) continue;
    if (!needsNewLine) {
        needsNewLine = true;
    } else {
        writer.append('\n');
    }
    writer.append(currentLine);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top