If I Receive the message - Printwriter not writing, what should I do?

296    Asked by AbigailAbraham in Java , Asked on Oct 12, 2022

 This program is compiling just fine, and the variables and such seem to be passing through. However, when I open the text file there is no data. Can anyone point me in the right direction or nudge my brain into the right process?


package dvd logger;
import java.util.*;
import java.io.*;
public class DVDLogger {
public DVDLogger() throws IOException
{
    String title = null;
    double price = 0;
    storeDVDInfo(title, price);
}
private void storeDVDInfo(String title, double price) throws IOException
{
    File path = new File("C:\users\crazy\desktop\dvd.txt");
    PrintWriter output = new PrintWriter(path);
    output.printf("%1$s %2$.2f", title, price); 
}
public static void main(String[] args) throws IOException{
    DVDLogger dvd;
    String title;
    double price;
    try (Scanner read = new Scanner(System.in)) {
        dvd = new DVDLogger();
        System.out.printf("%nPlease enter the title of the DVD: ");
        title = read.nextLine();
        System.out.printf("%nPlease enter the price of the DVD: ");
        price = read.nextDouble();
    }
    dvd.storeDVDInfo(title, price);
}
}


Answered by Nakayama Ueno

With any Java Writer or Stream... YOU MUST PROPERLY FLUSH AND CLOSE it.


The documentation is not fantastically clear... but:

when you exit the method, you must ensure that the file is flushed and closed. you are exiting your program before the data is written to disk.

Always use the following pattern when doing IO (if you are using Java7) and you receive the message - Printwriter not writing:

try (PrintWriter output = new PrintWriter(path)) {
    output.printf("%1$s %2$.2f", title, price);
    output.flush();
}
This is a 'try-with-resource' block.

Your Answer

Interviews

Parent Categories