0

I have a java code that automatically create a file for the user after login. It works properly when I run it in netbeans/intellij. However when I compiled it into a jar file, the program works but the file is not created. Can someone please help me?

Here is my code:

private void createTxtFile(){
    String loc = new File("").getAbsolutePath();
    String dir = loc+"/src/lists/"+user+"-"+pass+".txt";
    try {
        File myObj = new File(dir);
        if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
        } 
        else {
            JOptionPane.showMessageDialog(this, "User already have an existing list file.");
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "An error occured in creating file for your list.", "Error",JOptionPane.ERROR_MESSAGE);
    }
}
  • You shouldn't reference `src` in your code, `src` won't exist once the program is exported. You also can't create new directories/files that get stored in the jar at runtime, instead, you need to create them on the disk itself – MadProgrammer May 29 '22 at 06:55
  • 1
    One of the difficulties is finding a place to put the file, as the working directory may not be the same as the place the application is installed, even then you may not have write permissions to either of those locations. Instead, you need to store the file in a "well known" location. On Windows and MacOS, you can make use of common conventions and store these kind of things within the user's "home" directory – MadProgrammer May 29 '22 at 07:00
  • See [this example](https://stackoverflow.com/questions/27974857/where-should-i-place-my-files-in-order-to-be-able-to-access-them-when-i-run-the/27974989#27974989) and [this example](https://stackoverflow.com/questions/53974191/get-current-path-of-executed-file/53982349#53982349) for some more details – MadProgrammer May 29 '22 at 07:00
  • 1
    Everything @MadProgrammer says is of course correct. If that path doesn't *already* exist then you can't create it merely by creating a `File` object. You would have to use that class to create those directories. Take the advice and create a directory for your app off HOME and *then* the file in it – g00se May 29 '22 at 07:54

0 Answers0