簡體   English   中英

PrintWriter未寫入文件(Java)

[英]PrintWriter not writing to file (Java)

我正在編寫一種自動提款機程序,該程序會將數據輸出到文件中(是​​的,我知道它不是英語,但這不是重點),並且遇到了錯誤。

當我嘗試使用PrintWriter時不起作用,我不知道為什么。

    public void writeFooter(List<Purchase> list) throws Exception{

    int amountSold = 0;
    int amountNotSold = 0;

    int moneyRecieved = 0;

    openStreams();

    printer.println("Проданные товары: ");

    for(int i = 0; i <= list.size() - 1;i++){
        if(list.get(i).isSold()){
            writeToFile(list.get(i), dir);
            amountSold++;
            moneyRecieved += list.get(i).getPrice();
        }
    }
    printer.println();
    printer.println("Не проданные товары: ");
    for(int i = 0; i <= list.size() - 1; i ++){
        if(!list.get(i).isSold()){
            writeToFile(list.get(i), dir);
            amountNotSold++;
        }
    }

    printer.println();
    printer.println("Всего: "+list.size());
    printer.println("Кол-во проданно: "+ amountSold);
    printer.println("Кол-во не проданно: "+ amountNotSold);
    printer.println("Выручка: "+ moneyRecieved);

    printer.flush();

    System.out.print(printer.checkError());

    closeStreams();

}



private void openStreams() throws IOException{
    writer = new FileWriter(file,true);
    buffer = new BufferedWriter(writer);
    printer = new PrintWriter(buffer);
}
private void closeStreams() throws IOException{
    printer.flush();
    printer.close();
    buffer.close();
    writer.close();
}
    public void writeToFile(Purchase purchase,String dir) throws Exception{
    file = new File(dir);

    if(!file.exists()){
    file.createNewFile();
    }

    openStreams();

    printer.println(purchase.getName() + "   По цене:   " + purchase.getPrice() + "руб");

    closeStreams();
}

for循環有效,但是行。 這真的讓我感到困惑! 我嘗試過checkError( )並得到true ,但這仍然無濟於事。

有人可以解釋我在做什么錯嗎?

為什么要在writeToFile調用中打開和關閉流? 您不應該在for循環之前在writeFooter()中打開流,在編寫代碼的周圍放一個try塊,然后在finally節中關閉它們。

以我的方式來看,您首先在writeFooter中打開了流,然后您編寫了printer.println(“Проданныетовары:”);,然后for循環的第一次迭代調用writeToFile,將再次打開未關閉的流,即肯定會覆蓋第一行。

打開和關閉用於寫入一行的文件效率太低。

你需要類似的東西

writeFooter(...) {

  try {
    openStreams();
    writeToFile();
  } finally {
    closeStream();
  }
}

writeToFile只是簡單地寫入,不會打開或關閉流,而closeStream安全地關閉流,即檢查null等。

public static void studentAdd() throws IOException ,ClassNotFoundException{

    DataOutputStream output = new DataOutputStream(new FileOutputStream("Student.txt"));
    PrintWriter pr = new PrintWriter("Student.txt");
    Student7 student[] = new Student7[total];
    int STOP = 999;
    int stdID;
    int age;
    String address;
    String gender;
    String name;

    Scanner input = new Scanner(System.in);
    System.out.println("Please type  student ID or 999 to quit");
    stdID = input.nextInt(); 

    try {
        while(stdID != STOP) {  
            input.nextLine();
            output.writeInt(stdID);
            pr.print(stdID + "#");

            System.out.println("Please type student name");
            name = input.nextLine();
            output.writeUTF(name);
            pr.print(name + "#");

            System.out.println("Please type student age");
            age = input.nextInt();
            output.writeInt(age);
            input.nextLine();
            pr.print(age + "#");

            System.out.println("Please type student gender");
            gender = input.nextLine();
            output.writeUTF(gender);
            pr.print(gender + "#");                     

            System.out.println("Please type student address");
            address = input.nextLine();
            output.writeUTF(address);
            pr.print(address + "#");
            pr.println();

            System.out.println("Please type  student ID or 999 to quit");
            stdID = input.nextInt();
            }
        ;   pr.close();
            output.close();

    } catch (IOException e) { 
        System.err.println("Error is" + e.getMessage());
    } catch(InputMismatchException e) {
        System.err.println("Invalid Data Entry");
    }finally {
        studentMenu();
    }

} //end of stuadd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM