JFileChooser returns wrong file name?
final JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { String fileName = fc.getSelectedFile().getName(); String path = (new File(fileName)).getAbsolutePath(); }
The absolute path I get is the concatenation of the project directory and fileName!
Answers
Why are you getting the file name and instantiating a new File object again?
Can you try:
fc.getSelectedFile().getAbsolutePath();
That's what getAbsolutePath() does - gets the full path, including drive letter (if you're on Windows), etc. What are you trying to get, just the file name?
After you initialize your File object, you can get just the file name from that, OR you can use
If you're getting /path/to/filefilename but you're expecting /path/to/file/filename then you can add an extra slash to the path as appropriate.
Sure. Because you created new file new File(fileName) using returned filename, that means relative path. Use fc.getSelectedFile().getPath() or fc.getSelectedFile().getAbsolutePath() instead.