Frage

I have looked through some examples of how to write to a file in Java, and i thought i was doing it right.... apparently not. what is wrong here, it isn't even creating a file to write to. no error, just not writing to the file.

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
War es hilfreich?

Lösung

I reduced your code to a working example from which you can continue...

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();
   }
 }

}

Note that I have changed readFile(fileIn); to fileIn.next();to read from the Scanner. Did so, because you usedhasNext()` in the condition of the while-loop.

Andere Tipps

Java won't write to file when you use write, it will store all the data you want to write at the buffer untill you will flush or close it. In your case, a flush will be advised, because you writting to the file and reading it for changes, that results in reading data before you wrote the new data in.

You will need to use flush before reading the file. That means before theLine = readFile(fileIn);

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top