Question

I have tried reviewing old threads about this topic but none of the solutions seem to work for me. I have trying to write to a .txt file named "receipt.txt" but with the following code I am getting nothing. No file created (and obviously nothing in the file that doesn't exist) no errors just nothing.

//Write to File
 String fileName = "receipt.txt";
 try{
     PrintWriter writer = new PrintWriter(fileName);
     writer.println("Thank you for shopping with us");
     writer.println("Name: " + customerName);
     writer.println("Returning Customer: " + previousCustomer );
     writer.println("Phone: " + phoneNumber);
     writer.println("Shirt Type: " + shirtType);
     writer.println("Shirt Color: " + shirtColor);
     writer.println("Shirt Material: " + shirtMaterial);
     writer.println("Item Amount: " + itmAmt);
     writer.println("Total Cost: " + fmt3.format(totalCostMsg));
     writer.close();
     writer.flush();
     System.out.println("Receipt printed");      
 } catch (FileNotFoundException e) {
     e.printStackTrace();
 }
Was it helpful?

Solution

Your output is writen to the file named fileName

replace

PrintWriter writer = new PrintWriter("fileName");

with

PrintWriter writer = new PrintWriter(fileName);

EDIT:

Apparenttly you are just not looking for the file in wrong place, add the following statement to see where it has bee created:

System.out.println(new File(fileName).getAbsolutePath());

Also note that the order of close, flush is not correct. flush should be called first.

OTHER TIPS

PrintWriter writer = new PrintWriter("fileName");

should be

PrintWriter writer = new PrintWriter(fileName);

as you have already defined

String fileName = "receipt.txt";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top