Question

I've replaced many strings and outputted the result and now am trying to write those lines into a text file. Here's what I did. I created a new file:

File newfile = new File("/Users/Bill/Desktop/newfile.txt");
    if (newfile.exists()) {
        System.out.println("File exists");
    } else {
        newfile.createNewFile();
        System.out.println("New file created");

    }

And then I tried to write to the created file the result of System.out.println(lines[i]);

    try {
    WriteToFile newFile = new WriteToFile(newfile, true);
    newFile.write(lines[i]); 
    // lines[i] is what I used to print out System.out.println(lines[i])  
    }

    catch (IOException e) {
        System.out.println("Error.");
    }

I'm not getting what I'm expecting, though. Any suggestions?

WRITETOFILE:

public class WriteToFile {
private String path;
private boolean append = false;

public WriteToFile(String filename) {
    path=filename;
}

public WriteToFile(String filename, boolean appendfile){
    path=filename;
    append=appendfile;
}

public void write(String text) throws IOException {
    FileWriter filewrite = new FileWriter(path, append);
    PrintWriter print = new PrintWriter(filewrite);

    print.printf("%s" + "%n", text);
    print.close();
}
}
Was it helpful?

Solution

Every time you call WriteToFile.write, it reopens the file for writing, truncating the file's original contents. You should open the file once, in the constructor (and store the PrintWriter in a field), and add a close method that calls close for the PrintWriter.

On the calling side, do this:

WriteToFile writer = new WriteToFile(filename);
try {
    // writer.write(...);
} finally {
    writer.close();
}

By having the close call in a finally block, you ensure the file is closed even if an exception causes the function to quit early.

OTHER TIPS

Look at the 2nd argument of the FileWriter constructor in your code.

FileWriter filewrite = new FileWriter(path, append);

See, it says "append". Guess what it does. Read the documentation if you're unsure.

Now, look how you initialized append.

private boolean append = false;

This code is fully behaving as expected. It's just a developer's fault. Fix it :)

Just set fileName on System using the method System.setOut(fileName);

Then whenever we want to print using System.out.println() it will directly print to the fileName you mention.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top