繁体   English   中英

使用PrintWriter进行文件IO

[英]Using PrintWriter for file IO

好,所以我要开始拔头发了。 我以为文件输入有些棘手,但是哦,那还有文件输出。 我正在尝试将存储在对象中的坐标数组写入文件。 在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块周围对其进行调用,或者在throws方法声明的过程中声明该异常以稍后捕获它。

也可以看看:

始终避免使用绝对路径,因为相同的代码可能无法在另一个系统上运行。

我建议您将其放在resources文件夹下的项目中。

您可以根据文件位置尝试任何一种。

// Read from resources folder parallel to src in your project
File file1 = new File("resources/results.txt");

// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/results.txt").toURI());

您可能会忘记在while循环中增加i 添加i++以避免无限循环。

尝试

while (i++ < intersectionsIndex) {...}

要么

while (i < intersectionsIndex) {
   ...
   i++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM