Java Printwriter目标问题

Java Printwriter目标问题,java,file-io,printwriter,Java,File Io,Printwriter,我正在使用PrintWriter成功地将字符串写入文本文件,默认情况下,输出文本文件将写入我正在处理的Eclipse项目的目录 但我的Eclipse项目有一个名为Resources的特定文件夹,我希望将文本文件写入其中: 我的代码是: protected void saveCommandsToFile() throws FileNotFoundException, IOException { PrintWriter out = new PrintWriter("commands.txt"

我正在使用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();
}

正在引发FileNotFoundException。我该怎么做?谢谢大家!

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


或者,您可以使用项目中文件夹的完整路径。

以这种方式创建的
PrintWriter
需要一个路径,该路径可以是相对路径,也可以是绝对路径

相对路径是相对于工作目录的

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

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

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

即使您只是从Eclipse运行它,在项目文件夹中编写也不是最好的主意。不仅可能意外地覆盖源代码,而且代码的可移植性也不太好,如果以后决定将所有内容打包到jar文件中,您将发现无法再找到这些目录(因为它们都打包好了)。

请尝试下面的代码:

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 
Project
|
|___src
|
|___resources
    |
    |___commands.txt