【问题标题】:Java: Confused with these file I/O methods not functioningJava:对这些文件 I/O 方法不起作用感到困惑
【发布时间】:2026-02-10 14:50:02
【问题描述】:

我正在尝试实现一种将 Song() 对象数组写入文件以进行分配的方法。我对如何实现这一目标感到相当迷茫。我希望能够在 main 方法中调用该函数,但它似乎没有做任何事情。在这个阶段,这是一个测试,我希望它在运行 main() 时在命令行上打印。 这是我的代码:

    public static void main (String[] args)
    { //run the main program.
        Interface songUI = new Interface();
        songUI.run();

        try{
        PrintWriter outputTest = null;
        outputTest = write("testfile");
        read();
    }
    catch(IOException e){
        System.out.println("Caught!");
    }

    }


      public static PrintWriter write (String fileName) throws IOException{

      Scanner console = new Scanner(System.in);


      PrintWriter outFile = new PrintWriter(fileName);

      outFile.println ("Random numbers"); 

      for(int i=0; i<10; i++)
      {
          outFile.println ((int)( 1 + Math.random()*10) + " "); 
      }

      outFile.close();
      return outFile;
}

我还有一种方法可以从我试图在这里工作的文件中读取:

public static void read() throws IOException{

        String fileName = "test1";
        System.out.println ("The file " + fileName + "\ncontains the following lines:\n");
        Scanner inputStream = new Scanner (new File (fileName));

        while (inputStream.hasNextLine ())
        {
            String line = inputStream.nextLine ();
            System.out.println (line);
        }
        inputStream.close ();
}

如您所知,我很困惑,任何帮助都会令人惊叹。谢谢。

【问题讨论】:

标签: java file file-io exception-handling io


【解决方案1】:

您正在写信给testfile,但尝试从test1 读取。

代码组织不好。

  • 一个名为write()的方法不应该做任何其他事情,当然也不应该做输入
  • 返回已关闭的PrintWriter 完全没有意义。
  • write() 方法在内部捕获IOException,这使得调用者不可能知道失败。让它抛出IOException,就像read() 方法一样,让调用者处理它。

【讨论】: