0

我已经查看了一些如何在 Java 中写入文件的示例,我认为我做得对......显然不是。这里有什么问题,它甚至没有创建要写入的文件。没有错误,只是没有写入文件。

File inputFile = new File("pa2Data.txt");
File outputFile = new File("pa2output.txt");
Scanner fileIn = new Scanner(inputFile);
BufferedWriter fout = new BufferedWriter(new FileWriter(outputFile));

while(fileIn.hasNext()){
    String theLine = readFile(fileIn);
    fout.write("Infix expression: " + theLine + '\n');
    postfixExpression = infixToPostFix(theLine);
    String op = postfixExpression.toString();
    fout.write("Postfix Expression: " + op + '\n');

    theLine = readFile(fileIn);
    StringTokenizer st = new StringTokenizer(theLine);
    for(int i = 0; i < theValues.length; i++)
        theValues[i]  = Integer.parseInt(st.nextToken());
        int answer = postfixEval(postfixExpression, theValues);
        fout.write("Answer: " + answer + '\n' + '\n'); 
    }
    fileIn.close();
    fout.close();

}//end main
4

2 回答 2

1

Java不会在您使用时写入文件write,它会将您要写入的所有数据存储在缓冲区中,直到您愿意flushclose它为止。在您的情况下,flush将建议 a ,因为您写入文件并读取它以进行更改,这会导致在写入新数据之前读取数据。

您将需要flush在阅读文件之前使用。这意味着之前theLine = readFile(fileIn);

于 2013-11-05T19:04:29.973 回答
1

我将您的代码简化为一个工作示例,您可以从中继续...

public class Test{
  public static void main(String[] args){
    try {
      File inputFile = new File("pa2Data.txt");
      File outputFile = new File("pa2output.txt");
      Scanner fileIn = new Scanner(inputFile);
      BufferedWriter fout = new BufferedWriter(new FileWriter(outputFile));

      while(fileIn.hasNext()){
        String theLine = fileIn.next();
        fout.write("Infix expression: " + theLine + '\n');
      }
      fileIn.close();
      fout.close();
   } catch(Exception e){
      e.printStackTrace();
   }
 }

}

请注意,我已更改readFile(fileIn); tofileIn.next(); to read from the Scanner. Did so, because you usedhasNext()` 在 while 循环的条件下。

于 2013-11-05T19:19:04.597 回答