简体   繁体   中英

Java file is blank when Writing in a file

Appreciate the help. I am using Java and I want to write a text in the file. I am not sure what is wrong with my code. Is below code sufficient since it is a snippets of the program? I am trying to write a text in the file and there is no error. When I tried opening the file, the file is blank.

PharmacyReceipt = is the file where the system will read it and compute the total price PharmacyInvoice = if the money exceeds the total price, the system will write an invoice and delete the receipt file

Thank you

double change = 0;
                grandTotal = 0;
                try {
                    BufferedReader pharmacyFile = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
                    BufferedWriter write1 = new BufferedWriter(new FileWriter("pharmacyInvoice.txt", true));
                    String input_1;
                    System.out.printf("%-16s %-50.30s %-20s %-20s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
                    while ((input_1 = pharmacyFile.readLine()) != null) {

                        String[] data = input_1.split(",");
                        adminObject.setProductCode(data[0]);
                        adminObject.setName(data[1]);
                        adminObject.setPrice(Double.parseDouble(data[2]));
                        adminObject.setQuantity(Double.parseDouble(data[3]));
                        adminObject.setTax(Double.parseDouble(data[4]));
                        adminObject.setDiscount(Double.parseDouble(data[5]));

                        int MAX_CHAR = 40;
                        int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
                        //grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
                        //netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
                        netAmount = adminObject.getPrice() * adminObject.getQuantity();
                        System.out.printf("%-16s %-50.30s %-20.2f %-20.2f %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
                        //System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() +  "\t\t " + adminObject.getQuantity() +  "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());

                        grandTotal += netAmount;
                    }
                    System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
                    pharmacyFile.close();

                    System.out.print("Do you want to proceed to print the receipt? ");
                    choice_3 = sc.nextLine();
                    choice_3 = choice_3.toUpperCase();
                    if (choice_3.equals("YES") || choice_3.equals("Y")) {

                        System.out.print("\nHow much is the money? ");
                        double money = sc.nextDouble();

                        if (grandTotal <= money) {

                            BufferedReader groceryFile1 = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
                            System.out.printf("%-16s %-50.30s %-20s %-15s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
                            while ((input_1 = groceryFile1.readLine()) != null) {

                                String[] data = input_1.split(",");
                                adminObject.setProductCode(data[0]);
                                adminObject.setName(data[1]);
                                adminObject.setPrice(Double.parseDouble(data[2]));
                                adminObject.setQuantity(Double.parseDouble(data[3]));
                                adminObject.setTax(Double.parseDouble(data[4]));
                                adminObject.setDiscount(Double.parseDouble(data[5]));

                                int MAX_CHAR = 40;
                                int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
                                //grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
                                //netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
                                netAmount = adminObject.getPrice() * adminObject.getQuantity();
                                write1.write(adminObject.getProductCode() + "," + adminObject.getName() + "," + adminObject.getPrice() + "," + adminObject.getQuantity() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "\n");
                                System.out.printf("%-16s %-50.30s %.2f\t\t %.2f\t\t %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
                                //System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() +  "\t\t " + adminObject.getQuantity() +  "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
                                
                            }
                            write1.write("___________________________________________________");
                            write1.write("\nGrand Total = PHP %.2f\n\n" + grandTotal);
                            write1.write("Money: " + money + "\n");
                            write1.write("Change: " + (change = money - grandTotal) + "\n");
                            write1.write("___________________________________________________\n");
                            System.out.println("___________________________________________________\n");
                            System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
                            System.out.println("Money: " + money + "\n");
                            System.out.println("Change: " + (change = money - grandTotal) + "\n");
                            System.out.println("___________________________________________________\n");
                            
                            
                        }
                    } else {
                        System.out.println("___________________________________________________\n");
                        System.out.println("***Money exceeds the amount.***");
                        System.out.println("___________________________________________________\n");
                    }
                    pharmacyFile.close();

                } catch (FileNotFoundException e) {
                    System.out.println("File Not Found" + e);
                } catch (IOException e) {
                    System.out.println("File Not Found");
                } catch (NumberFormatException e) {
                    System.out.println(e);
                } catch (Exception e) {
                    System.out.println(e);
                }
                break;

You have to close the writer at the end via writer1.close() . Because you have a BufferedWriter, it is not writing to the file always immediately. If then your program for example exits before it can write, your content to the file, it will remain blank.

Also you should just in general always close this kind of resources at the end as they might cause memory leaks and other problems. You can do it via:

try (FileWriter writer1 = new FileWriter(new File("blablub")) {
    // ... do your stuff with the writer
}

This is called a try-with-resources clause and will close the Resource in the end automatically. The more explicit version is:

FileWriter writer1 = new FileWriter(newFile("blablub"));
try {
    // ... do your stuff with the writer
} catch (Exception ex) {
   ...
} finally {
   writer1.close();
}

Edit: It might be, that you are thinking that you are closing the writer1 as I've now seen, but actually you have two calls to pharmacyFile.close(). Maybe this is your issue.

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