Hello guys, I've been testing things for a while since i'm learning java; I'm doing a playlist editor/creator and most of the problems I have are due to swing, and here comes my question. I used JFileChooser to open files without any problem, the FileNameExtensionFilters worked well, but now i'm a bit disoriented about what to do when saving with different file extensions, here's an example code:
This isn't working, it saves files without any extension unless I explicitly include the extension in the name when I select the file to save
I can already tell that the FileNameExtensionFilters only work when selecting files to be opened, but I still haven't figured out yet how to make extensions work. How can I force file extensions when saving according to the selected FileNameExtensionFilter? Any leads on this would be helpful, thanks in advance
JFileChooser gives you a selectedFile. Remember that a java.io.File isn't a computer file in the usual sense; the API makes it clear that it is (emphasis added)
An abstract representation of file and directory pathnames.
What you do with the pathname before you use it to create a physical file on disk is up to you. .
Most programs resort to appending a suitable extension if the user-selected file is not valid. You can easily do the same, using JFileChooser#getFileFilter() to get a reference to the selected filter; call its accept(File f) method to determine whether the file name is acceptable; if not, cast the reference and call FileNameExtensionFilter#getExtensions() to get the desired extension.
There are no new questions, but there may be new answers.
It works now and this is the corrected snippet. This only works with single extension filefilters since I only do a getExtensions() method call. Filters with multiple extensions won't allow me to know which extension is the chosen one, neither the chosen File path if I don't explicitly name it with the desired extension so I can't do it this way ... I can't come with a workaround to this but neither do I need to implement it now. At least I know a little more about this matter now
larry clay wrote:This only works with single extension filefilters since I only do a getExtensions() method call. Filters with multiple extensions won't allow me to know which extension is the chosen one
Use a separate filter for each extension and like I already said, use getFileFilter() to get the selected filter.