Printwriter destination issue

2019-07-05 04:50发布

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.

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

My code is:

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();
}

If I change the line to:

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

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

3条回答
一纸荒年 Trace。
2楼-- · 2019-07-05 05:24

The path you are specifying is an absolute path. If you want it to be relative to where you're running the java program try using "./Resources/commands.txt".

Alternative you could use the full path to the folder within your project.

查看更多
虎瘦雄心在
3楼-- · 2019-07-05 05:25

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

Relative paths are relative to the working directory.

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.

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.

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).

查看更多
够拽才男人
4楼-- · 2019-07-05 05:26

Try below code:

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();
        }
    }
}

Here is the project folder structure:

Project
|
|___src
|
|___resources
    |
    |___commands.txt 
查看更多
登录 后发表回答