PrintWriter not writing to file (Java)

旧街凉风 提交于 2020-01-21 18:56:06

问题


I am writing a kind of a cash machine program that will output the data into a file (Yes, I know its not in English, but that's not the point) and I am experiencing an error.

When I try to use PrintWriter it doesn't work, I don't know why.

    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();
}

The for loops work, but the lines. It really confuses me! I have tried checkError() and I get true, but that still doesn't help.

Can someone please explain what am I doing wrong?


回答1:


Why are you opening and closing stream in your writeToFile call ? Shouldn't you open the streams in writeFooter() before the for loop, put a try block around the writing code, and close them in a finally section .

The way I see it, You've openedstream first in the writeFooter, the you write printer.println("Проданные товары: ");, and then your for loop's first iteration calls writeToFile, will again open the non-closed stream, that will surely overwrite the first printed line.

Opening and closing File for writing one line is way too inefficient.

You need something like

writeFooter(...) {

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

Where writeToFile simply writes , doesn't open or close stream, and closeStream safely closes the streams, i.e. check for null etc.




回答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


来源:https://stackoverflow.com/questions/13745260/printwriter-not-writing-to-file-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!