0

I'm using System.setProperty("apple.awt.fileDialogForDirectories", "true"); to only select folders. When I execute new java.io.File(fd.getFile()).getAbsolutePath();, it always returns /Users/<user>/Desktop/<folder>. Say I select /Users, it will return /Users/<user>/Desktop/Users. How can I fix it?

Code:

if (System.getProperty("os.name").toLowerCase().contains("mac")) {
        System.setProperty("apple.awt.fileDialogForDirectories", "true");

        FileDialog fd = new FileDialog(this, "Choose a folder to save streams", FileDialog.LOAD);
        fd.setDirectory(saveStreamLocTB.getText());

        fd.setVisible(true);

        String loc = new java.io.File(fd.getFile()).getAbsolutePath();
        if (loc != null) {
            p.setSaveStreamLoc(loc);
            saveStreamLocTB.setText(loc);
        }

        System.setProperty("apple.awt.fileDialogForDirectories", "false");
    }

edit I need the full path

dimo414
  • 47,227
  • 18
  • 148
  • 244
  • Why are you using `apple.awt`? Java provides a [cross-platform file-chooser dialog](https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) that can be easily configured to only select folders. – dimo414 Aug 03 '16 at 00:15
  • If you don't want an absolute path, why are you using `getAbsolutePath()`? – user207421 Aug 03 '16 at 01:56

2 Answers2

1

fd.getFile() returns a relative path, and new File() will create a new File relative to the execution directory:

By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

So by the time you call .getAbsolutePath() the path you're working with is already mangled.

Calling fd.getDirectory() + fd.getFile() works, but you should avoid constructing file paths with string concatenation - that's what the two-argument File constructor is for, so instead do:

String loc = new File(fd.getDirectory(), fd.getFile()).getAbsolutePath();

That said Java 7 introduced the much more flexible and powerful Path class, and wherever possible I'd suggest using it over File. Along the same lines Swing includes a cross-platform file-chooser dialog that will be much easier to work with than Apple's old awt APIs. There's also DirectoryChooser if you want to try JavaFX.

dimo414
  • 47,227
  • 18
  • 148
  • 244
0

I got it!

This

String loc = new java.io.File(fd.getFile()).getAbsolutePath();

needed to be this

String loc = fd.getDirectory() + fd.getFile();