Search code examples
javainno-setupfilewriterlaunch4j

Java FileWriter. How do you create a folder in the same directory as your .exe file?


public void saveFile() {
        
         try {
             try (BufferedWriter save = new BufferedWriter (new FileWriter("Lessons\\" + tempTextField.getText() + ".txt"))) { // creates the file
                 save.write(lessonPane.getText()); // saves the contents of the text pane into file
                 JOptionPane.showMessageDialog(null, "File Saved!");
             }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e);
        }

this is what I currently have, and right now it's working just fine. But for this to work, I have to create a folder in the project directory or else it will throw me an error, saying the location is missing.

the problem is that I want to make an .exe file and installer for this project (because its a project requirement in school). And after I build, and make .exe using L4J, and installer using ISC, it will throw me an error saying that the target location (aka. the folder "Lessons") is invalid / missing.

after trying to solve it, I think the reason that its no longer working is because, my .jar .exe. and the JRE are in the folder "dist" (generated after I clean and build the project to get the .jar file) while the folder "Lessons" is on the root folder.

How can I make it that the folder will be automatically generated on the same location as the .jar or .exe. Honestly, I dont even know if that's possible. And is there any other way to work around this problem?

Thanks a lot!


Solution

  • public void saveFile() {
            
            File fdir = new File("Lessons");
            if (!fdir.exists()) {
                if(fdir.mkdirs()){
                    System.out.println("directory created");
                } else {
                    System.out.println("folder creation failed");
                }
            } else {
                System.out.println("directory already exists");
            }
            
             try {
                 try (BufferedWriter save = new BufferedWriter (new FileWriter("Lessons\\" + tempTextField.getText() + ".txt"))) { // creates the file
                     save.write(lessonPane.getText()); // saves the contents
                     JOptionPane.showMessageDialog(null, "File Saved!");
                 } 
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, e);
            }
    

    this is just silly, I just removed the slashes from the File and it worked. I dont know how or why did it worked. But it worked.