Printwriter, кажется, не выводит в указанный файл после добавления цикла while - PullRequest
0 голосов
/ 06 февраля 2012

Я на начальной стадии проекта для школы и уже столкнулся с ошибкой. Если я просто экспортирую содержимое списка массивов с помощью цикла for без цикла while, все работает нормально, но когда я хочу использовать цикл while для предоставления опций, выходной текстовый файл не содержит ничего, как если бы программа просто ничего не делал, но создал пустой текстовый файл. Я очень смущен.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.PrintStream;
import javax.swing.JOptionPane;
import java.util.Arrays;

public class studentProcessor
{
   public static void main(String[] args) throws FileNotFoundException
   {  
      PrintStream pr=System.out;
      String inputFileName = JOptionPane.showInputDialog("Input file:");
      String outputFileName = JOptionPane.showInputDialog("Output file:");
      File inputFile = new File(inputFileName);
      Scanner in = new Scanner(inputFile);
      PrintWriter out = new PrintWriter(outputFileName);
      ArrayList<Student>student = new ArrayList<Student>();
      while (in.hasNextLine())
      {
          student.add(new Student(in.nextInt(), in.next(), in.nextDouble()));
      }
      in.close();
      boolean done=false;
      while (!done)
        {
            String m=JOptionPane.showInputDialog("Please enter the number for the action which you would like to perform." +
                "\n1. Add new student(s)\n2. Remove student(s)\n3. Update student's data\n4. Search for student" +
                "\n5. Sort students\n6. Create GPA report\n7. Output information to a .txt file\n0. Exit");
            if (m.equals("1"))
            {
                JOptionPane.showMessageDialog(null, "Add new student(s)");
            }
            else if (m.equals("2"))
            {
                JOptionPane.showMessageDialog(null, "Remove student(s)");
            }
            else if (m.equals("3"))
            {
                JOptionPane.showMessageDialog(null, "Update student's data");
            }
            else if (m.equals("4"))
            {
                JOptionPane.showMessageDialog(null, "Search for a student");
            }
            else if (m.equals("5"))
            {
                JOptionPane.showMessageDialog(null, "Sort students");
            }
            else if (m.equals("6"))
            {
                JOptionPane.showMessageDialog(null, "Create GPA report");
            }
            else if (m.equals("7"))
            {
                JOptionPane.showMessageDialog(null, "Output information to a .txt file");
                out.println("The students' information is listed below:");
                for (Student Stu:student)
                {
                    out.println(Stu.getId()+" "+Stu.getLName()+" "+Stu.getGpa());
                }
            }
            else if (m.equals("0"))
            {
                System.exit(0);
                done=true;
            }
            else 
            {
                JOptionPane.showMessageDialog(null, "You have not entered a valid command, try again.");
            }
        }
      out.close();
   }
}

и вот класс ученика, которым я пользуюсь.

class Student
{ 
 private int id;
 private String lName;
 private double gpa;

 public Student (int studentId, String studentLName, double studentGpa)
   { 
     id=studentId;
     lName=studentLName;
     gpa=studentGpa;
   }

 public int getId()
   { return id; }

 public String getLName()
   { return lName; }

 public double getGpa()
   { return gpa; }

 public void setId(int id)
   { this.id=id; }

 public void setLName(String lName)
   { this.lName=lName; }

 public void setGpa(double gpa)
   { this.gpa=gpa; }

}

спасибо за любую помощь =]

РЕДАКТИРОВАТЬ: это новый раздел кода, который теперь работает с printwriter. спасибо за помощь!

else if (m.equals("7"))
        {
            String outputFileName = JOptionPane.showInputDialog("Designate an output file for student information:");
            PrintWriter out = new PrintWriter(outputFileName);
            out.println("The students are listed below:");
            for (Student Stu:student)
            {
                out.println(Stu.getId()+" "+Stu.getLName()+" "+Stu.getGpa());
            }
            out.close();
        }

Ответы [ 3 ]

2 голосов
/ 06 февраля 2012

Проблема в том, что строка с out.close никогда не вызывается.

Метод System.exit завершает работу приложения перед закрытием программы записи на печать.

Вы должны использовать блок try finally для закрытия своих ресурсов.

Также ваш код был бы более понятным, если бы вызов System.exit выполнялся в конце метода, а не в цикле while. Вы уже используете логическое значение для завершения цикла, поэтому дайте ему завершиться и перейдите к остальной части кода.

1 голос
/ 06 февраля 2012

Вам необходимо очистить выходной поток после записи в него:

out.flush();

Кроме того, вы захотите создать выходной поток, когда пользователь выберет ваш вариант записи (7).В противном случае вы будете записывать записи в один и тот же файл несколько раз.Так что-то вроде этого:

     } else if (m.equals("7")) {
        JOptionPane.showMessageDialog(null,
              "Output information to a .txt file");
        final PrintWriter out = new PrintWriter(outputFileName);
        out.println("The students' information is listed below:");
        for (Student Stu : student) {
           out.println(Stu.getId() + " " + Stu.getLName() + " "
                 + Stu.getGpa());
        }
        out.close();
     } 
1 голос
/ 06 февраля 2012

Пробовали ли вы выполнить очистку () PrintWriter перед закрытием?

...