0

When I run this as a jar, this .properties file is created on the desktop. For the sake of keeping things clean, how can I set the path to save this file somewhere else, like a folder? Or even the jar itself but I was having trouble getting that to work. I plan on giving this to someone and wouldn't want their desktop cluttered in .properties files..

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class DataFile {
public static void main(String[] args) {

    Properties prop = new Properties();
    OutputStream output = null;

    try {

        output = new FileOutputStream("config.properties");

        prop.setProperty("prop1", "000");
        prop.setProperty("prop2", "000");
        prop.setProperty("prop3", "000");

        prop.store(output, null);

    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
  }     
}
Oscar F
  • 323
  • 2
  • 9
  • 21
  • What is it for? Perhaps the [Preferences API](http://docs.oracle.com/javase/8/docs/technotes/guides/preferences/index.html) would be more appropriate? – David Conrad Sep 15 '14 at 21:16
  • The properties file? I'm just using it to store some information entered by the user so that the next time the program is run, that information isn't erased. – Oscar F Sep 15 '14 at 21:19
  • You have two choices, change the "start in" reference of the link that starts your program or specify a absolute path reference – MadProgrammer Sep 15 '14 at 21:29

1 Answers1

0

Since you are using the file name without a path, the file you creates ends in the CWD. That is the Current working directory the process inherits from the OS. That is is you execute your jar file from the Desktop directory any files that use relative paths will end in the Desktop or any of it sub directories.

To control the absolute location of the file you must use absolute paths. An absolute path always starts with a slash '/'.

Absolute path:

/etc/config.properties

Relative path:

sub_dir/config.properties

The simplest way is to hard code some path into the file path string.

output = new FileOutputStream("/etc/config.properties");

You can of course setup the path in a property which you can pass using the command line instead of hard coding it. The you concat the path name and the file name together.

String path = "/etc";
String full_path = "/etc" + "/" + "config.properties";
output = new FileOutputStream(full_path);

Please note that windows paths in java use a forward slash instead of back slash. Check this for more details file path Windows format to java format

Community
  • 1
  • 1
YairCarel
  • 82
  • 3