簡體   English   中英

簡單的文件寫入,但它不起作用

[英]Simple file writing, but its not working

我已經看了一些如何用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

當您使用write ,Java不會寫入文件,它會將您要寫入的所有數據存儲在緩沖區中,直到您將flushclose它。 在您的情況下,將建議flush ,因為您寫入文件並讀取它以進行更改,這會導致在您寫入新數據之前讀取數據。

在讀取文件之前,您需要使用flush 這意味着在theLine = readFile(fileIn);

我將您的代碼縮減為一個可以繼續的工作示例...

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); to readFile(fileIn); to fileIn.next(); to read from the Scanner. Did so, because you used to read from the Scanner. Did so, because you used在while循環的條件下to read from the Scanner. Did so, because you used hasNext()`。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM