简体   繁体   中英

How can I prevent PrintWriter from printing a blank line at the beginning of each file?

I'm trying to write a couple of methods to save a binary tree to a file. They work correctly, except for a slight problem. The problem is that a blank line is inserted at the beginning of each file that's created. Why is PrintWriter doing this, and how can I prevent it from happening?

Here's my code:

import java.io.*;

void callSaveGame(String fileName) throws IOException {
    PrintWriter out = new PrintWriter(new FileWriter("X:\\path\\to\\save\\directory\\" + fileName)); // associate PrintWriter with file

    saveGame(root, out);

    out.close();
}

void saveGame(Node current, PrintWriter out) {
    if (current != null) {
        out.println(current.getData()); // print node to file

        saveGame(current.getLChild(), out); // call for left child(ren)

        saveGame(current.getRChild(), out); // call for right child(ren)
    }
}

It is not PrintWriter that is inserting the blank line. PrintWriter won't do that.

The actual cause of the problem is not shown in the code snippet you provided, but if the code is an accurate reflection of your real application, then the offending blank line is already in the result of the first getData() call.

Try to use out.print(current.getData()) instead of println() . It helped me to resolve this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM