gpt4 book ai didi

java - 简单的文件写入,但不起作用

转载 作者:行者123 更新时间:2023-12-02 06:34:30 26 4
gpt4 key购买 nike

我浏览了一些如何用 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

最佳答案

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

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); fileIn.next();从扫描仪读取。这样做是因为您在 while 循环的条件中使用了hasNext()`。

关于java - 简单的文件写入,但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com