1

データをファイルに出力する一種のキャッシュ マシン プログラムを作成しています (英語ではないことはわかっていますが、それは重要ではありません)。エラーが発生しています。

使おうとする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、 が表示されましたが、それでも解決しません。

誰かが私が間違っていることを説明できますか?

4

2 に答える 2

0
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
于 2013-02-05T02:54:59.667 に答える
0

writeToFile 呼び出しでストリームを開いたり閉じたりするのはなぜですか? for ループの前に writeFooter() でストリームを開き、書き込みコードの周りに try ブロックを配置し、finally セクションでそれらを閉じるべきではありませんか。

私の見方では、最初に writeFooter でストリームを開き、println("Проданные товары: "); を書き、次に for ループの最初の繰り返しで writeToFile を呼び出し、閉じられていないストリームを再び開きます。最初に印刷された行を確実に上書きします。

1行書くためにファイルを開いたり閉じたりするのは非効率です。

次のようなものが必要です

writeFooter(...) {

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

writeToFile は単純に を書き込み、ストリームを開いたり閉じたりせず、closeStream は安全にストリームを閉じます。つまり、null などをチェックします。

于 2012-12-06T14:31:10.070 に答える