Reputation: 8342
String filePath = chooser.getSelectedFile().getAbsoluteFile() + ".html";
I'm adding the extension hard coded and then saving to it. I would like my app to be portable across platforms so adding .html manually may make this a Windows only solution.
If I want to save the file in another format, text for example, how do I detect which format the user selected? FileNameExtensionFilter
can add filters to the dialog but how do I get the return value for file type selected? From this I'm still unclear how to retrieve user selected file type.
alt text http://img98.imageshack.us/img98/4904/savef.jpg
How can I find out which of two filters the user selected as the save format? HTML or JPEG, how do I retrieve this info from JFileChooser? It has something to do with JFileChooser.getFileFilter()
.
Upvotes: 3
Views: 11916
Reputation: 382
You're probably looking for this:
The trick consists in casting the returned FileFilter to FileNameExtensionFilter and then apply getExtensions().
JFileChooser fileChooser = new JFileChooser("");
// Prevent user to use the default All Files option
fileChooser.setAcceptAllFileFilterUsed(false);
[...]
// Get the FileFilter
FileFilter ff = fileChooser.getFileFilter();
// Cast the FileFilter to FileNameExtensionFilter
FileNameExtensionFilter extFilter = (FileNameExtensionFilter)ff;
// Get the Extension
String ext = extFilter.getExtensions()[0];
Or, for making it compact:
ext = ((FileNameExtensionFilter)fileChooser.getFileFilter()).getExtensions()[0];
Upvotes: 1
Reputation: 8342
Here is the code snippet that solves the issue:
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML Documents", "htm", "html");
chooser.setFileFilter(filter);
int option = chooser.showSaveDialog(ChatGUI.this);
if (option == JFileChooser.APPROVE_OPTION) {
// Set up document to be parsed as HTML
StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
HTMLEditorKit kit = new HTMLEditorKit();
BufferedOutputStream out;
try {
System.out.println(chooser.getFileFilter());
if (chooser.getFileFilter() == filter)
System.out.println("ha ha");
}
}
Upvotes: 2
Reputation: 8204
I don't understand what it is you're trying to do. Are you trying to save the selected file in some other format than it already is of? The path of the selected file will contain the file extension, so you don't need to add it manually. The following, for example, will print "/Users/banang/Documents/anything.html" to the screen if the file anything.html is selected.
JFileChooser chooser = new JFileChooser();
chooser.showSaveDialog(null);
System.err.println(chooser.getSelectedFile().getCanonicalPath());
Please try to clarify your question a bit.
Upvotes: 0