简体   繁体   中英

How to create a file/folder from jar in Java?

I have converted my JavaFX project into a jar file and these posts helped me to successfully read media files from my local environment that are needed in my project:

Now at one part of the project I need to create a folder in my pc during the project runtime, that will store some data gained through the program. Now I am using this command to execute that purpose:

String file_name= String.valueOf(Main.class.getResource("data stored/"+name+"-"+Long.toString(time)));
    new File((file_name)).mkdirs();

Here I just followed the similar steps that I used for reading the file ( Which is mentioned in the attached posts). But when I run the jar file, everything works fine except that, the folder is not created. And if I don't write this part: Main.class.getResource , the jar file shows an error which is obvious. I think the reason might be, for reading, it needs the reference of the main class, but for creating a folder, referring with respect to a class is not correct.

My path of main class: src/brainwave/Main.java

Path of the folder I want to create: src/data stored

Any suggestion please how can I solve this issue? Thanks.

getResource will retrieve a path into the JAR file, in case the class file is also coming from there; otherwise a normal path, if not running from JAR.

Use a plain File to get a path to a file/directory (eg new File("data/files/") ) that is not saved in the JAR

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