2014-03-06 32 views
1

我已成功使用PrintWriter将字符串写入文本文件,并且默认情况下会将输出文本文件写入正在处理的Eclipse项目的目录中。Printwriter目标问题

但我的Eclipse项目已要求我想要的文本文件写入到资源的特定文件夹:

我的代码是:

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。我如何解决这个问题?谢谢!

回答

1

A PrintWriter创建这种方式会期望一条路径,它可以是相对路径或绝对路径。

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

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

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

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

即使您只是从Eclipse运行它,写在您的项目文件夹不是最好的想法。不仅可能无意中覆盖源代码,而且代码也不会很轻便,如果稍后决定将所有东西打包到jar文件中,则会发现无法找到这些目录任何更多(因为他们都打包)。

0

您指定的路径是绝对路径。如果你想让它与你正在运行java程序的地方相关,请尝试使用"./Resources/commands.txt"

替代方案,您可以使用项目文件夹的完整路径。

1

试试下面的代码:

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