【问题标题】:Printwriter does not seem to output to specified file after I add a while loop添加while循环后,Printwriter似乎没有输出到指定文件
【发布时间】:2012-02-06 17:19:46
【问题描述】:

我正处于学校项目的早期阶段,并且已经遇到了错误。如果我只是使用 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();
   }
}

这是我正在使用的 Student 类。

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

【问题讨论】:

  • 为什么会有 System.exit(0);将 done 设置为 false 将导致程序终止并希望正确关闭 outfile。

标签: java while-loop printwriter


【解决方案1】:

问题是永远不会调用带有 out.close 的行。

System.exit 方法在关闭打印编写器之前终止您的应用程序。

你应该使用 try finally 块来关闭你的资源。

如果 System.exit 调用位于方法的末尾而不是 while 循环中,您的代码也会更清晰。您已经在使用布尔值来终止循环,所以让它终止,然后继续执行其余代码。

【讨论】:

  • 感谢您指出 system.exit() 我在更改为布尔值后忘记将其删除。我还发现了我的问题,并在我想使用它而不是在程序开始时在循环中初始化输出文件的字符串。
【解决方案2】:

您需要在写入后刷新输出流:

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

【讨论】:

  • 为了从另一个答案继续我的评论,我将 out.close() 移到了您显示的位置,它现在运行良好。 idk,如果它只是我放置 out.close 的地方,或者是因为我也移动了 out 文件的字符串的初始化。我将发布我所做的似乎有效的编辑
  • 不过,我想问一下,PrintWriter 之前的“最终”是否会对代码的运行方式产生巨大影响?抱歉,我是新手,这是我第一次尝试这个复杂的程序。
  • 使用 final 标记变量可以提升您的程序 - 因为它允许编译器进行某些类型的优化。如果你把它排除在外,它不是杀手。
【解决方案3】:

您是否尝试在关闭 PrintWriter 之前对其进行刷新()?

【讨论】:

  • closures 会刷新 writer,问题是 close 方法没有被调用。
猜你喜欢
  • 2021-11-17
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
相关资源
最近更新 更多