【问题标题】:PrintWriter not writing to file (Java)PrintWriter 不写入文件(Java)
【发布时间】:2012-12-06 14:04:34
【问题描述】:

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

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

谁能解释一下我做错了什么?

【问题讨论】:

  • 你的意思是它不起作用?你有例外吗?
  • “不起作用”是什么意思?错误信息/症状是什么?

标签: java file-io printwriter


【解决方案1】:

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

在我看来, 您首先在 writeFooter 中打开了流,然后编写了 printer.println("Проданные товары:");,然后您的 for 循环的第一次迭代调用 writeToFile,将再次打开未关闭的流,这肯定会覆盖第一个打印的行。

为了写一行而打开和关闭文件效率太低了。

你需要类似的东西

writeFooter(...) {

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

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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • 请对此“答案”发表评论。在没有任何评论的情况下发布裸代码以及它与问题的相关性并没有太大帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    相关资源
    最近更新 更多