PrintWriter没有写入文件(Java)

时间:2012-12-06 14:04:35

标签: java file-io printwriter

我正在编写一种现金机程序,将数据输出到一个文件中(是​​的,我知道它不是英文的,但这不是重点)而且我遇到了错误。

当我尝试使用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,但这仍然无济于事。

有人可以解释一下我做错了什么吗?

2 个答案:

答案 0 :(得分:0)

为什么要在writeToFile调用中打开和关闭流? 你不应该在for循环之前打开writeFooter()中的流,在编写代码周围放一个try块,然后在finally部分中关闭它们。

我看到的方式, 你首先在writeFooter中打开流,你编写printer.println(“Проданныетовары:”);然后你的for循环的第一次迭代调用writeToFile,将再次打开非封闭流,这肯定会覆盖第一次打印线。

打开和关闭用于写一行的文件效率太低。

你需要像

这样的东西
writeFooter(...) {

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

writeToFile只是写入,不打开或关闭流,closeStream安全地关闭流,即检查null等。

答案 1 :(得分: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