Printwriter目的地问题

时间:2014-03-06 19:04:37

标签: java file-io printwriter

我使用PrintWriter成功地将字符串写入文本文件,默认情况下,输出文本文件将写入我正在处理的Eclipse项目的目录中。

但我的Eclipse项目有一个名为Resources的特定文件夹,我希望将文本文件写入:

我的代码是:

protected void saveCommandsToFile() throws FileNotFoundException, IOException {
    PrintWriter out = new PrintWriter("commands.txt");
    int listsize = list.getModel().getSize();
    for (int i=0; i<listsize; i++){
        Object item = list.getModel().getElementAt(i);
        String command = (String)item;
        System.out.println(command);    //use console output for comparison
        out.println(command);
    }
    out.close();
}

如果我将该行更改为:

    PrintWriter out = new PrintWriter("/Resources/commands.txt");

正在抛出FileNotFoundException。我该如何解决这个问题?谢谢!

3 个答案:

答案 0 :(得分:3)

以这种方式创建的PrintWriter将期望一个路径,可以是相对路径也可以是绝对路径。

相对路径相对于工作目录。

另一方面,绝对路径需要包含根目录(或目录,当它发生)的完整路径,因此在Windows系统上它将类似于c:/foo/bar.txt,在Unix类型的系统上/home/nobody/foo/bar.txt

可以找到关于绝对和相对路径的确切规则here

关于使用相对路径的说明。当你依赖它们时要小心,因为你无法知道你的工作目录是什么:当你运行你的应用程序时从Eclipse开始,它将默认为你的项目目录,但是如果你将它打包并从命令行运行,它将在其他地方。

即使您只是从Eclipse运行它,在项目文件夹中写入也不是最好的想法。不仅可能意外覆盖您的源代码,但您的代码将不会非常便携,如果您稍后决定将所有内容打包在jar文件中,您将发现您将无法找到这些目录更多(因为他们都打包了)。

答案 1 :(得分:2)

尝试以下代码:

protected static void saveCommandsToFile() throws FileNotFoundException, IOException {
    File file = new File("resources/commands.txt");
    System.out.println("Absolute path:" + file.getAbsolutePath());
    if (!file.exists()) {
        if (file.createNewFile()) {
            PrintWriter out = new PrintWriter(file);
            out.println("hi");
            out.close();
        }
    }
}

这是项目文件夹结构:

Project
|
|___src
|
|___resources
    |
    |___commands.txt 

答案 2 :(得分:0)

您指定的路径是绝对路径。如果您希望它与您运行java程序的位置相关,请尝试使用"./Resources/commands.txt"

备选方案,您可以使用项目中文件夹的完整路径。