How to get absolute path to files from FileDialog in SWT?

lynxoid picture lynxoid · Feb 21, 2012 · Viewed 8.1k times · Source

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)?

Answer

Edward Thomson picture Edward Thomson · Feb 21, 2012

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.