1

I have an odd situation where I want to perform a test on the user inputted value of the filename in a JFileChooser.

The .getSelectedFile() function returns a file based on both the user inputted value of the filename and the directory which is not what I want.

As an example: The current directory in the JFileChooser might be "C:\a\b\c" The user inputted value might be "d\e\f.txt"

.getSelectedFile() returns "C:\a\b\c\d\e\f.txt" .getSelectedFile().getName() returns "f.txt"

Whereas I want something like .getInputtedFile() to return "d\e\f.txt"

Is there an available solution like this or would I have to extend JFileChooser?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Wolsie
  • 144
  • 1
  • 13
  • The reason for this is because we want the user to be able to enter a filename such as: server1\dir\xx.dat server2\xx.dat where if we detect that they manually entered these names (as opposed to a directory happening to be of that name) we would use that as an "absolute path" and handle it our own way. – Wolsie Nov 21 '14 at 13:33

2 Answers2

1

The inputted value, "d\e\f.txt", is a relative path. It is logic that .getSelectedFile() returns "C:\a\b\c\d\e\f.txt", because the specified path is appended to the current directory. If you specify an absolute path, for sure it will not be concatenated.

Andrei G
  • 660
  • 5
  • 12
  • 20
  • I know that. I am asking if there is a way just to get what the user entered. – Wolsie Nov 21 '14 at 13:32
  • 1
    It would make no sense. The file chooser always should return the absolute path of the selected file. What the user inputs, it is not so important. And the absolute file path should be enough for you. – Andrei G Nov 21 '14 at 13:40
0

As far as I know, there is no build in way to retrieve the relative path from a selected file (but I could be wrong).

But you can help yourself by creating a method like this:

public static String getRelativeSubdirectory(final File file) {
    final File currentFolder = new File("");
    if (file.getAbsolutePath().startsWith(currentFolder.getAbsolutePath())) {
        return file.getAbsolutePath().substring(currentFolder.getAbsolutePath().length() + 1);
    }
    return file.getAbsolutePath();
}

This method accepts a File argument and returns a String with the relative path if the selected file is in a subdirectory of the current folder. If not, it will return absolute path of the given file. So this method won't return relative paths like ../../dir/subdir/file.txt.

This solution has major similarities to this answer.

Community
  • 1
  • 1
Tom
  • 16,842
  • 17
  • 45
  • 54