I need to use
fileChooser.getSelectedFile()
method however it always returns language modified path because some directories are translated in osX. For example folder "/Downloads" is translated to my system language "/Stiahnuté" but real path is "/Downloads"
return:
/Users/John/Stiahnuté
expectation
/Users/John/Downloads
If I select some sub-directory then fileChooser.getSelectedFile() returns right path again. It looks that always only last directory in path is translated
/Users/John/Downloads/subDirectory
Code:
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FolderFilter());
fileChooser
.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("save path: "
+ selectedFile.getPath());
doSomething(selectedFile);
}
}
});
UPDATE:
I made little workaround but it is not perfect solution. However it works for me.
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Directories", "dir");
fileChooser.setFileFilter(filter);
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
File newDir = new File(selectedFile.getPath());
if (!newDir.exists()) {
newDir.mkdir();
}
doSomething();
}
I can reproduce the problem on Mac OS X 10.11.4 with Java 1.8.0_66. For me this looks like a bug (or at least unexpected behavior) in the implementation of JFileChooser. You may open a bug report for the issue.
With the help of an answer explaining to use FileDialog to get a operating system native file chooser and another answer about using it to select directories I found the following workaround:
final Frame parent = …; // can be null
System.setProperty("apple.awt.fileDialogForDirectories", "true");
final FileDialog fileDialog = new FileDialog(parent);
fileDialog.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
final File selectedDirectory = new File(fileDialog.getDirectory(), fileDialog.getFile());
System.out.println(selectedDirectory);
System.out.println(selectedDirectory.exists());
Note that using "apple.awt.fileDialogForDirectories" is, of course, platform specific and will not work on other operating systems.
Related
The following JFileChooser code works fine, except that the FileFilter doesn't filter. It doesn't do anything. From another stackoverflow answer: "Filename filters do not function in Sun's reference implementation for Microsoft Windows."
Comment from Nov 21st, 2016
Is there a FileFilter workaround for Windows?
public String getPathFileName(String startingDir) {
String returnSelectedFile = "";
JFileChooser fileChooser = new JFileChooser(startingDir);
FileFilter filter = new FileNameExtensionFilter("Excel file", "xls", "xlsx");
fileChooser.addChoosableFileFilter(filter);
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
returnSelectedFile = selectedFile.getPath();
}
return returnSelectedFile;
}
I have found this to work:
final JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("CSV FILES", "csv"));
I have found that this works for one file filter, but I cannot confirm for multiple file filters. Hope this helps.
I have several dialog boxes which provide a File Chooser. For the first, my coding was like this
JFileChooser chooser= new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal= chooser.showOpenDialog(this);
if(returnVal==JFileChooser.APPROVE_OPTION){
File f= chooser.getSelectedFile();
jTextField1.setText(f.getPath());
chooser.setCurrentDirectory(f);
}
In my case, i would like to set the last path which is selected as the default path in next selection JFileChooser. Is there any solution for me?
Thanks for any response
Depending on your requirements, you can use Preferences to store it away and use it again after the program has been restarted.
Preferences pref = Preferences.userRoot();
// Retrieve the selected path or use
// an empty string if no path has
// previously been selected
String path = pref.get("DEFAULT_PATH", "");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Set the path that was saved in preferences
chooser.setCurrentDirectory(new File(path));
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
chooser.setCurrentDirectory(f);
// Save the selected path
pref.put("DEFAULT_PATH", f.getAbsolutePath());
}
You will have to "remember" the last path.
This can easily be done by storing the value in a instance variable...
private File lastPath;
//...
lastPath = f.getParentFile();
And simply resetting it when you need to...
//...
if (lastPath != null) {
chooser.setCurrentDirectory(lastPath);
}
You could also use a single instance of the JFileChooser, so each time you show it, it will be at the last location it was used...
I have next code:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNajitPDFCache) {
JFileChooser chooser;
String choosertitle = "Select directory.";
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setApproveButtonText("OK");
//
// disable the "All files" option.
//
chooser.setAcceptAllFileFilterUsed(false);
//
if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
textFieldPDFCache.setText(chooser.getCurrentDirectory()+"");
}
}
}
That's Ok. I choose c:\test folder in opened chooser form and next I click on button OK.
But chooser.getCurrentDirectory() return only c:\ . Why? What is wrong?
getCurrentDirectory() returns the current directory that is opened in the
JFileChooser. When you are selecting C:\test you opened C:\ directory, so you are getting C:\ on getCurrentDirectory()
The getSelectedFile() returns the file that is selected (in your case the file is a directory). So you if you want the directory that is selected by the user use getSelectedFile()
You should use chooser.getSelectedFile() instead.
You Can Set Canonical path as
File Canonicalpath = new File(new File("C:/").getCanonicalPath());
I'm trying to save a file using JFileChooser. However, I seem to be having some trouble with it. Here's my code:
if (e.getSource() == saveMenu) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
FileNameExtensionFilter xmlFilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");
// add filters
chooser.addChoosableFileFilter(xmlFilter);
chooser.setFileFilter(xmlFilter);
int result = chooser.showSaveDialog(Simulation.this);
if (result == chooser.APPROVE_OPTION) {
writeToXML(chooser.getSelectedFile());
}
}
This doesn't force the file to have a .xml extension, so I've tried to use the following code to force the file to be saved with the extension .xml
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter xmlWriter = null;
try {
xmlWriter = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(f+".xml"), "UTF8"),
format);
However, with this I can't prevent the user from writing xpto.xml in the JFileChooser and if they do that, the file will have "two extensions": it will be a file named xpto.xml.xml
So my questions are:
How can I make the JFileChooser save an xml file by default?
If the user inserts a file name like xpto.xml, how can I save it as xpto.xml and not xpto.xml.xml?
As you've noticed, JFileChooser doesn't enforce the FileFilter on a save. It will grey-out the existing non-XML file in the dialog it displays, but that's it. To enforce the filename, you have to do all the work. (This isn't just a matter of JFileChooser sucking -- it's a complex problem to deal with. Your might want your users to be able to name their files xml.xml.xml.xml.)
In your case, I recommend using FilenameUtils from Commons IO:
File file = chooser.getSelectedFile();
if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("xml")) {
// filename is OK as-is
} else {
file = new File(file.toString() + ".xml"); // append .xml if "foo.jpg.xml" is OK
file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName())+".xml"); // ALTERNATIVELY: remove the extension (if any) and replace it with ".xml"
}
There's also some ideas for what to do if you want multiple types in the save dialog here: How to save file using JFileChooser?
Just to make things clear as to how to use the JFileChooser to save files.
//set it to be a save dialog
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
//set a default filename (this is where you default extension first comes in)
chooser.setSelectedFile(new File("myfile.xml"));
//Set an extension filter, so the user sees other XML files
chooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));
now the user was encouraged to save the item as an xml file in this example, but they may not have actually set it.
if(chooser.showSaveDialog(this) == jFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().toString();
if (!filename .endsWith(".xml"))
filename += ".xml";
//DO something with filename
}
This is the most simple case, if you have multiple possible file formats, then you should catch the selected filter, verify THAT extension, and also save the file according to the selected format. but if you are doing that, you are probably an advanced java programmer and not utilizing this post.
How about something like this:
else if (e.getSource() == saveMenu) {
int returnVal = chooser.showSaveDialog(Simulator.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String fname = file.getAbsolutePath();
if(!fname.endsWith(".xml") ) {
file = new File(fname + ".xml");
if(!file.createNewFile()) {
/*check with user??*/
}
You should try this:
if(!file.getName().contains(".")) file = new File(file.toString() + ".xml");
You should try this. I did this and it worked.
FileOutputStream fileOut = new FileOutputStream(file1+".xml");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
I'm using the JFileChooser to allow a user to choose a .txt file that will later be processed by my program, however when the user chooses the file, it is actually opened by my computers default app (in my case TeXworks) as well as used by my program. Any idea how I can stop this?
File fileToOpen = fileChooser.getSelectedFile();
JFileChooser's getSelectedFile() method, returns a File object.
Use the getAbsolutePath() to get the absolute name to the file.
Modified example from the JavaDoc:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this directory: " + chooser.getSelectedFile().getAbsolutePath());
}
So in your case you just need to append .getAbsolutePath() to the end of your statement, like this:
File fileToOpen = fileChooser.getSelectedFile().getAbsolutePath();