4

I am using SWT's FileDialog to let user select several files:

FileDialog dlg = new FileDialog(s, SWT.MULTI);
dlg.setFilterPath(somePath);
String fn = dlg.open();
if (fn != null)
  String [] files = dlg.getFileNames()

While fn returns the absolute path to the directory, the files array contains relative paths. I would like to get an absolute path for each file. Is there a way of doing this in Java that works across platforms (Win, Linux, MacOS)?

lynxoid
  • 509
  • 6
  • 14

1 Answers1

7

You need to append the filename to the given filter path. To avoid worrying about path separators and the like, you can just use the File class. For example:

String[] filenames = dialog.getFileNames();
String filterPath = dialog.getFilterPath();

File[] selectedFiles = new File[filenames.length];

for(int i = 0; i < filenames.length; i++)
{
    if(filterPath != null && filterPath.trim().length() > 0)
    {
        selectedFiles[i] = new File(filterPath, filenames[i]);
    }
    else
    {
        selectedFiles[i] = new File(filenames[i]);
    }
}

If you need the path as a String, you can of course use the getAbsolutePath() method on the resultant Files.

Edward Thomson
  • 74,857
  • 14
  • 158
  • 187