gpt4 book ai didi

java - 使用 PrintWriter 进行文件 IO

转载 作者:行者123 更新时间:2023-12-01 18:29:45 25 4
gpt4 key购买 nike

好吧,我要开始拔头发了。我认为文件输入有点棘手,但是天哪,还有文件输出。我正在尝试将存储在对象中的坐标数组写入文件。在 C++ 中,这很容易,但看在上帝的份上,我无法弄清楚这一点。

public static void outFile(int intersectionsIndex, Coordinate arg[], Coordinate avgPoint) {

File file = new File("resource/result.txt");
file.getParentFile().mkdirs();

PrintWriter writer = new PrintWriter(file);
int i = 0;
while (i < intersectionsIndex) {
writer.print(arg[i].getX());
writer.print(" ");
writer.println(arg[i].getY());
i++;
}
writer.print("Predicted Coordinate: ");
writer.print(avgPoint.getX());
writer.print(" ");
writer.println(avgPoint.getY());
writer.close();

return;
}

无论我使用哪种 IO 方法,我都会不断收到相同的错误。我在这里关注了一些有类似问题的帖子,但没有成功。有什么建议或其他方法吗?我可能缺少一些基本的东西。

编辑:抱歉错误是

Error:(83, 30) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

这是“PrintWriter writer = newPrintWriter(file); 行。

更新:问题已解决。工作代码如下:

public static void outFile(int intersectionsIndex, Coordinate arg[], Coordinate avgPoint) throws Exception{

File file = new File("resource/result.txt");
file.getParentFile().mkdirs();

PrintWriter writer = new PrintWriter(file);
int i = 0;
while (i < intersectionsIndex) {
writer.print(arg[i].getX());
writer.print(" ");
writer.println(arg[i].getY());
i++;
}
writer.print("Predicted Coordinate: ");
writer.print(avgPoint.getX());
writer.print(" ");
writer.println(avgPoint.getY());
writer.close();

return;
}

最佳答案

看起来您收到的错误实际上是编译时错误,而不是运行时错误。

构造函数PrintWriter(File)在其签名中声明了一个已检查的FileNotFoundException,因此您需要用try ... catch包围它的调用code> block ,或者在方法的 throws 声明中声明该异常以便稍后捕获它。

另请参阅:

关于java - 使用 PrintWriter 进行文件 IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791932/

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