印刷机目的地问题 [英] Printwriter destination issue

查看:85
本文介绍了印刷机目的地问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am successfully writing strings to a text file with the PrintWriter, and by default the output text file is written to the directory of the Eclipse project I'm working on.

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

But my Eclipse project has a specific folder called Resources that I want the text file to be written to:

我的代码是:

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.我该如何解决?谢谢!

The FileNotFoundException is being thrown. How do I get around this? Thank you!

推荐答案

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

A PrintWriter created this way will expect a path, which can be either relative or absolute.

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

Relative paths are relative to the working directory.

绝对路径需要包含根目录(或目录,如果发生的话)的完整路径,因此在Windows机器上,它将是c:/foo/bar.txt之类的东西,在Unix类型的系统中,它是.

Absolute paths on the other hand need to contain the full path from the root directory (or directories, as it happens), so on a Windows box it'll be something like c:/foo/bar.txt, on Unix-type systems /home/nobody/foo/bar.txt.

关于绝对路径和相对路径的确切规则可以在这里.

The exact rules on absolute and relative paths can be found here.

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

A note though on the use of relative paths. Be careful when you're relying on them because you have no way of knowing what your working directory is going to be: when you run your application from Eclipse, it will default to your project directory but if you package it up and run from command line, it will be somewhere else.

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

And even if you're only running it from Eclipse, writing in your project folder isn't the best of ideas. Not only is it possible to accidentally overwrite your source code, but your code won't be very portable, if later on you decide to package everything up in a jar file, you'll find you won't be able to find those directories any more (because they're all packaged up).

这篇关于印刷机目的地问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆