1

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();
}
}
lrvilnius
  • 107
  • 1
  • 3
  • 8

3 Answers3

2

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.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
0

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.

0

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • No, reopening the file for every write is still a bad idea, even if you open it in append mode. (Also, it's not portable. Windows has no append mode, for example---it's simulated using at-end mode.) – C. K. Young May 24 '11 at 11:52