【问题标题】:Unable to perform file IO in java无法在java中执行文件IO
【发布时间】:2012-08-13 15:51:59
【问题描述】:

我是 java 的初学者,并为后缀评估编写了以下问题。虽然该程序适用于控制台 IO。使用文件时有问题。我试图在文件output00.txt 中获取程序的答案,但文件为空。 这是代码。我省略了与此问题无关的方法。

public static void main(String[] args) throws Exception  {


     FileReader input = new FileReader("input00.txt");
        BufferedReader in = new BufferedReader(input)   ;
        FileWriter output = new FileWriter("output00.txt");
        BufferedWriter out = new BufferedWriter(output);
        while (true)  {
          String lineReader = in.readLine();
          if (lineReader==null) {
              break;
          }
          Stack<String> m_Stack = new Stack<String>();

          m_Stack.addAll(Arrays.asList(lineReader.trim().split("[ \t]+")));

          if (m_Stack.peek().equals("")){
              continue;
          }
          try  {
            double finVal = evaluateRPN(m_Stack);
            if (!m_Stack.empty()) {
                throw new Exception();
            }
            out.write(finVal + "\n");
          }
          catch (Exception e)  {System.out.println("error");}
        }
      }

文件 input00.txt 包含

8 9 +
7 6 -
7 7 * 9 -

【问题讨论】:

  • 您是否在正确的位置寻找输出文件?尝试删除并查看它是否被重新创建。代码看起来不错,只是您没有关闭输出流。顺便说一句,这是作业吗?

标签: java file-io bufferedreader


【解决方案1】:

您必须关闭流。试试out.close()

【讨论】:

    【解决方案2】:

    您需要调用out.flush() 来刷新您已写入文件的内容,或者调用out.close() 来自动刷新已缓冲的内容。实际上,无论如何你都应该调用close(),因为这是一种很好的做法,如果有办法让你退出 while() 循环的话。

    【讨论】:

    • 很好的答案,但在关闭流时有点太放松了。无论如何,您必须致电close() - 不应该。因为这是唯一有效的方式。
    • 循环内部有一个 catch 块,它似乎没有做任何事情,只是输出错误然后允许循环再次运行。你应该用 catch 包裹循环,并用 out.close() 方法添加一个“finally”,以确保你清理干净。
    【解决方案3】:

    您可以尝试在写语句后添加out.flush()。然后它将缓冲区写入文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 2012-06-08
      • 2015-04-29
      • 1970-01-01
      • 2017-03-13
      相关资源
      最近更新 更多