简体   繁体   English

写入文件时Java文件为空

[英]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.我正在使用 Java,我想在文件中写入文本。 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 PharmacyReceipt = 是系统将读取它并计算总价的文件 PharmacyInvoice = 如果金额超过总价,系统将开具发票并删除收据文件

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() .您必须在最后通过writer1.close()关闭writer1.close() Because you have a BufferedWriter, it is not writing to the file always immediately.因为您有一个 BufferedWriter,它不会总是立即写入文件。 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.这称为 try-with-resources 子句,最终会自动关闭资源。 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().编辑:可能是,您认为您正在关闭我现在看到的 writer1,但实际上您有两次对 pharmacyFile.close() 的调用。 Maybe this is your issue.也许这是你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM