【问题标题】:Java writeout program Unhandled exception type IOExceptionJava 写出程序 Unhandled exception type IOException
【发布时间】:2012-11-19 03:46:44
【问题描述】:

我的这部分程序出现多个错误。它的基本作用是从一个无组织的文件 PersonnelInfo.txt 中读取输入,并将其排序到 EmployeeInfo 类中的一个数组中(未发布,因为我不相信问题出在该类中,如果你们愿意,我会贴出来供参考)。

在对信息(如姓名、身份证号、公司头衔等)进行排序后,程序将其写入另一个文件 ORGANIZEDPersonnelInfo.txt,该文件将按如下方式排序:

姓名:此处为员工姓名

ID:此处为员工 ID

等等

我遇到的一个错误是在“静态 FileWriter writeOut...”行中,它是“未处理的异常类型 IOException。我在主方法声明中放置了一个 throws IOException,但它什么也没做。

接下来,在“public String toString()”方法中,我收到了多个错误。当我尝试使其无效时,它说返回类型与 Object.toString() 不兼容。当我将其保留为字符串并返回 null 时,它希望我使用 try/catch,但主要错误仍然存​​在。

请帮忙!这越来越令人沮丧...

import java.io.*;
import java.util.Scanner;

public class HR {

static EmployeeInfo[] employee = new EmployeeInfo[4];
static FileWriter writeOut = new FileWriter("/Users/zach/Documents/workspace/Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
static BufferedWriter out = new BufferedWriter(writeOut);


public static void main(String[] args) throws IOException {
    File PersonnelInfo = new File("/Users/zach/Documents/workspace/Dec. 10, 2012/src/PersonnelInfo.txt");
    Scanner inputFile = new Scanner(PersonnelInfo);

    int numOfEmployees = Integer.parseInt(inputFile.nextLine());
    System.out.println("Number of employees: " + numOfEmployees);



    for (int i = 0; i < 4; i++) {
        String name = inputFile.nextLine();
        String ID = inputFile.nextLine();
        String title= inputFile.nextLine();
        String startDate = inputFile.nextLine();
        employee[i] = new EmployeeInfo(name, ID, title, startDate);
    }

    listEmployeeInfo();
    employee.toString();

}


public String toString() {
    for (EmployeeInfo i: employee) {
        out.write("Name: " + i.getName());
        out.write("ID: " + i.getID());
        out.write("Title: " + i.getTitle());
        out.write("Start Date: " + i.getStartDate());
    }
    return null;
}

【问题讨论】:

    标签: java methods ioexception throws


    【解决方案1】:

    如果您覆盖toString()(正如您所做的那样,因为 toSTring() 是 Object 的一个方法,并且您正在您的类中重新定义它,它像所有类一样扩展 Object),您应该尊重合同被覆盖的方法,它是返回对象的字符串表示形式(而不是将字段写入缓冲的写入器。用另一个名称命名此方法。

    此外,您正在调用一个引发检查异常的方法 (out.write()):IOException。所以,要么你知道如何处理这个异常,你应该捕获它,或者你不知道如何处理它,并且方法应该声明它抛出异常:

    public void writeToOut() throws IOException {
        for (EmployeeInfo i: employee) {
            out.write("Name: " + i.getName());
            out.write("ID: " + i.getID());
            out.write("Title: " + i.getTitle());
            out.write("Start Date: " + i.getStartDate());
        }
    }
    

    您的程序中还有其他编译错误。每个都带有一条错误消息、一个文件名和一个行号。尝试理解消息并修复错误。阅读Java tutorial about exceptions 了解如何处理它们。

    如果您在阅读本教程后仍然无法处理它们,请提出另一个问题并粘贴您从编译器获得的确切错误消息。

    【讨论】:

      【解决方案2】:

      当您执行static void main 时,您不在HR 类的实例中,而是在它的静态方法中。所以如果你想使用你写的toString()方法,你就必须使用new HR().toString()

      最好从所有字段中删除 static 关键字并创建HR 对象的实例,然后在该对象的构造函数中打开文件,即

      public HR() {
        try {
          this.writeOut = new FileWriter("/Users/zach/Documents/workspace/Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
        } catch (IOException e) {
           // handle it, etc.
        }
      }
      
      public void processFile() {
        // Do the stuff
      }
      
      public static void main(String[] args) {
        HR myHR = new HR().processFile();
        // etc.
      }
      

      这将允许您使用 toString() 方法并允许您以您想要的方式处理异常。

      【讨论】:

        【解决方案3】:

        其他人有 toString() 的地址,所以我将在 FileWriter 上一试...

        我会将writeOut 填充到方法而不是静态作用域中,这样您就可以捕获异常,甚至尝试不同的文件名或其他内容:

        FileWriter openOutputfile(String name)
        {
            boolean done = false;
            FileWriter result = null
            try {
                result = new FileWriter(...);
                done = true;
            }
            catch(IOException ex) {
                // print the stack trace
                // prompt for another filename
                // name = read line
            }
            return result;
        }
        

        【讨论】:

          【解决方案4】:

          我建议将 Writer 的静态声明移到 main 中,原因有两个(一个是它们不需要是静态属性,并且 IOException 正在那里处理)。从toString获取字符串并使用writer将字符串写入文件中:

            public class HR {
          
              static EmployeeInfo[] employee = new EmployeeInfo[4];
          
          
              public static void main(String[] args) throws IOException {
                   FileWriter writeOut = 
                              new FileWriter("/Users/zach/Documents/workspace/"+
                                             "Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
                   BufferedWriter out = new BufferedWriter(writeOut);
          
                   File PersonnelInfo = new File("/Users/zach/Documents/workspace/"+
                                                 "Dec. 10, 2012/src/PersonnelInfo.txt");
                   Scanner inputFile = new Scanner(PersonnelInfo);
          
                   ....
                   //write employee string in the file
                   out.write(getEmployeeString());
                   out.close();
              }
          
              public String getEmployeeString() {
               StringBuilder stringBuilder = new StringBuilder();
               for (EmployeeInfo i: employee) {
                    stringBuilder.append("Name: " + i.getName());
                    stringBuilder.append("ID: " + i.getID());
                    stringBuilder.append("Title: " + i.getTitle());
                    stringBuilder.append("Start Date: " + i.getStartDate());
               }
               return stringBuilder.toString();
             }       
           }
          

          如果您必须将它们设为静态变量,则在静态块中进行初始化,异常处理如下:

               static FileWriter writeOut;
               static BufferedWriter out;
          
               static {
                  try{
                     writeOut = 
                              new FileWriter("/Users/zach/Documents/workspace/"+
                                             "Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
                        out = new BufferedWriter(writeOut);
                   }catch(IOException ioex){
                         ioex.printStackTrace();
                   }
               } 
          

          【讨论】:

          • 非常感谢,这个解决方案让程序写入文件,但现在它正在写入 [LEmployeeInfo;@39617189,所以我需要弄清楚发生了什么。
          • @Zach 这是我这边的简单错误。而不是out.write(employee.String());(在员工类上调用toString方法)它应该只是out.write(toString());,但这看起来不太好,因此我建议将您的方法名称从toString()更改为getEmployeeString()并使用@987654328 @。我更新了答案。
          【解决方案5】:

          更正 toString()

          public String toString() {
              StringBuffer buf = new StringBuffer();
              for (EmployeeInfo i: employee) {
                  buf.append("Name: ").append(i.getName());
                  buf.append("ID: ").append(i.getID());
                  // ....
              }
              return buf.toString();
          }
          

          主要打印内容:

          HR hr = new HR();
          out.write(hr.toString());
          

          但我会使用自己的写方法“writeEmployees(out)”来写 请参阅海报 JB Nizet 的解决方案

          【讨论】:

          • 它写入文件,但我得到 [LEmployeeInfo;@18872380 我也会选择直接写入文件,但是对于这个项目,我们需要使用一种方法。
          • Hr hr = new Hr(); out.write(hr.toString());
          • 但现在有点难看。
          • 使用JB Nizet的解决方案,这样的方法的意思是:
          • 是的,它有效,但不是很好,这是尽可能少地更改原始代码的方法。
          猜你喜欢
          • 1970-01-01
          • 2018-02-23
          • 2018-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-20
          • 2022-12-01
          • 2013-10-04
          相关资源
          最近更新 更多