1

我试图让我的程序将输出保存到文件中以进行调试。问题是,它编译时没有任何错误,而不会在任何地方创建文件。这可能是非常简单的事情,但我想不通,有一段时间没有用 Java 编码了。

public static void main(String[] Args) {
    FileOutputStream out = null;
    try {
        out = new FileOutputStream("out.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    PrintWriter ps = new PrintWriter(out);
    for (int l = 1; l < 1001; l++) {
        ps.println((translation(makeString(l))));
        System.out.println((translation(makeString(l))));
    }
    try {
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

提前致谢!

4

3 回答 3

2

您正在创建没有绝对路径的 FileOutputStream。结果将相对于程序的当前目录。下面展示了如何给出一个绝对路径。

public static void main(String[] Args) {
    FileOutputStream out = null;
    try {
        out = new FileOutputStream("c:\\out.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    PrintWriter ps = new PrintWriter(out);
    for (int l = 1; l < 1001; l++) {
        ps.println((translation(makeString(l))));
        System.out.println((translation(makeString(l))));
    }
    try {
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

将使您的文件出现在 C: 驱动器根文件夹...

于 2012-10-30T12:26:21.737 回答
1

如果您在 Eclipse 中运行此代码,请在workspace/project文件夹中搜索,您应该在那里找到一个

于 2012-10-30T12:27:12.597 回答
1

如果文件不存在,则 FileOutputStream 创建文件:请参阅FileOutputStream(java.lang.String)

运行该文件时,该文件将位于当前目录中。要查看代码的运行位置,请添加以下行:

System.out.println(new java.io.File(".").getAbsolutePath());

这将打印出当前的工作目录。

于 2012-10-30T12:29:13.920 回答