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); } } 
4
  • 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 Commented May 29, 2022 at 6: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 Commented May 29, 2022 at 7:00
  • See this example and this example for some more details Commented May 29, 2022 at 7: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 Commented May 29, 2022 at 7:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.