简体   繁体   中英

Specify a Relative Path from a Package for a new File

I'm trying to create a File object in order to save my properties file. I need to know how to specify a relative path from my package though because the below code does not work.

    try {
        File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties");
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            properties.store(fileOutputStream, null);
        }
    } catch (IOException | URISyntaxException ioe) {
        System.out.println(ioe);
    }

Relative path depends on current working directory from where you are running your program.

If you are running in IDE, IDE may set working directory path to Project directory. And How your program run depends on classpath to jar/claases in your program.

Just replace this line:

File file = new File("/com/configuration/settings.properties");

with:

File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM