gpt4 book ai didi

java - 是否可以使用同一个 FileWriter 文件并通过多种方法写入它?

转载 作者:行者123 更新时间:2023-11-30 05:42:58 27 4
gpt4 key购买 nike

我正在从用户处获取输入文件和输出文件,并尝试从 main 方法和 towerOfHanoiMoves 方法写入输出文件。我尝试将输出变量作为参数传递给 towerOfHanoiMoves 方法,但不断收到错误。

我收到的错误是:

 Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type IOException 
at TowerofHanoiRecursive.towerOfHanoiMoves(TowerofHanoiRecursive.java:72)
at TowerofHanoiRecursive.main(TowerofHanoiRecursive.java:41)

有没有办法让我可以通过两种不同的方法写入同一个输出文件?

我尝试过使用 PrintWriter,但这给了我同样的结果。我还尝试过在 towerOfHanoiMoves 方法中刷新并关闭 outStream,但这也不起作用。我还导入了所有必需的 java.io 文件,但由于某种原因它们没有显示在此处。

public class TowerofHanoiRecursive{


public static void main(String[] args) throws IOException, EmptyFile,
FileNotFoundException{
int n; //number of disks

String rodLeft = "A", rodRight = "C", rodMiddle = "B";
FileReader inputStream = null;
FileWriter outputStream = null;
BufferedReader str = null;

try {
outputStream = new FileWriter(args[1]); // output file
inputStream = new FileReader(args[0]); // input file
str = new BufferedReader(inputStream);
String nextLine;
File newFile = new File(args[0]);

if (newFile.length()==0) { //Tests if input file is empty
//if file is empty, the EmptyFile exception will be thrown
throw new EmptyFile("Input file is empty");

}

while ((nextLine = str.readLine()) != null) {
outputStream.write("----------------------------------------"
+ "------------------------\n");
outputStream.write("Number of Disks in Starting Tower = "
+ nextLine);
n = Integer.parseInt(nextLine);

towerOfHanoiMoves(n, rodLeft, rodRight, rodMiddle,
outputStream);

}

}catch (FileNotFoundException e) {
outputStream.write("Input file not found.);
outputStream.flush();
if (outputStream != null) outputStream.close();

}catch (EmptyFile e) {
outputStream.write(e.getMessage());
outputStream.flush();
if (inputStream != null) inputStream.close();
if (outputStream != null) outputStream.close();
str.close();
} finally {
outputStream.write("");
outputStream.write("\n\nSuccess!);
outputStream.flush();

if (inputStream != null) inputStream.close();
if (outputStream != null) outputStream.close();
str.close();
}

}


public static void towerOfHanoiMoves(int n, String leftRod, String
rightRod, String MidRod, FileWriter outStream) {

if (n == 1) {
outStream.write("Move disk 1 from ....");
}
}
}

最佳答案

特定的错误是 write() 方法可能抛出 IOException。因此,必须捕获或声明该异常。因此,可以修改 towerOfHannoiMoves 以抛出 IOException

    public static void towerOfHanoiMoves(int n,
String leftRod,
String rightRod,
String MidRod,
FileWriter outStream)
throws IOException

另一个注意事项:发布的代码缺少一些闭合引号。例如,

outputStream.write("Input file not found.);

关于java - 是否可以使用同一个 FileWriter 文件并通过多种方法写入它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55346902/

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