【问题标题】:Printwriter destination issue打印机目的地问题
【发布时间】:2014-03-06 19:04:36
【问题描述】:

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

【问题讨论】:

    标签: java file-io printwriter


    【解决方案1】:

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

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

    另一方面,绝对路径需要包含从根目录(或目录,碰巧)的完整路径,所以在 Windows 机器上,它会类似于 c:/foo/bar.txt,在 Unix 类型系统上 @987654324 @。

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

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

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

    【讨论】:

      【解决方案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 
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-09-02
          • 1970-01-01
          • 1970-01-01
          • 2018-01-24
          • 1970-01-01
          • 1970-01-01
          • 2014-12-22
          相关资源
          最近更新 更多