-1

When I call method

System.out.print(new File("").getAbsolutePath())

from main I get the project workspace

C:\Users\darkr\Desktop\NuovoWorkSpace\ProjectName.

When it gets called by our save() method, which serializes what we need, suddenly the absolute path given from

new File("").getAbsolutePath()

becomes System32 (for me) and Desktop directory for my colleagues.

We're using gitHub to share our changes but this makes it almost impossible.

  • try using Path class to get the file/directory path. **String path = Paths.get("").toAbsolutePath().toString()**; – Volzy Jan 22 '22 at 09:23

1 Answers1

1

The code you have new File("").getAbsolutePath() is commonly used to determine the current directory from where you launched your application's main(String[]) method. So it looks like you are running from C:\Windows\System32 not on desktop folder.

The easiest way to fix your issue is to edit your application shortcut (see .lnk file and set "Start in" folder), or cd to be in an appropriate writable directory before running your application, or change your application to use file chooser to pick the target location for saves.

Alternatively pick sensible output paths for writing to instead of "", some good candidates are:

// Local user profile
File folder = new File(System.getenv("LOCALAPPDATA"), "myfolder"); 
// Roaming user profile
File folder = new File(System.getenv("APPDATA"), "myfolder"); 
// Temp folder:
File folder = new File(System.getProperty("java.io.tmpdir"), "myfolder")

Some sites suggest one of the following lines to locate Desktop, but this is unreliable because it will not work if the folder has been moved or run on some non-English installations:

File maybeDesktop = new File(System.getProperty("user.home"), "Desktop");
Path maybeDesktop = Path.of(System.getProperty("user.home"), "Desktop");

If you want to read the exact location of user Desktop from Java, you need to use JNI/JNA/Panama call to Windows API functions SHGetFolderPath or SHGetKnownFolderPath.

DuncG
  • 12,137
  • 2
  • 21
  • 33
  • Yes. Use an AppData subdirectory in Windows, $HOME/Library/Support on Mac, $HOME/.local/share in Linux. – VGR Jan 22 '22 at 15:03