set the JFileChooser to open current directory - java

I created a JFileChooser to open a file, but when I select a file and open it,for second the time that i want to select a file, the JFileChooser is not in the current directory.
How set the JFileChooser to open the current directory?
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
int result = fileChooser.showOpenDialog( this );
if ( result == JFileChooser.APPROVE_OPTION ){
File fileName = fileChooser.getSelectedFile();
File path=fileChooser.getCurrentDirectory();
if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
{
JOptionPane.showMessageDialog( this, "Invalid File Name",
"Invalid File Name", JOptionPane.ERROR_MESSAGE );
}
else{
currentPath=path.getPath()+"\\"+fileName.getName();}
}

Either pass the directory into the constructor via the File parameter (a File can also be a directory, FYI), or use the .setCurrentDirectory(File dir) method before you make the JFileChooser visible.
Also, to make the JFileChooser stay in the same folder, you need to save the folder of the file/directory chosen from last time, and use THAT value to control which folder it starts in the subsequent times via .setCurrentDirectory(File dir)

Make the chooser a class level attribute and create it only once. That way, it not only points to where it did when closed, but will have the same size, location, file filter selected etc.

Related

JFileChooser, save multiple file types

I have no problem opening multiple file types, however I want the option to be able to save multiple file types. I can't figure out how to get the option the user selected to save their file types as.
Here is my code:
//.txt and .encm files are allowed
final JFileChooser txtOrEncmChooser = new JFileChooser(new File(System.getProperty("user.dir")));
//only allow user to use .txt and .encm files
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Encrypted Data File (*.encm)", "encm"));
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
txtOrEncmChooser.setAcceptAllFileFilterUsed(false);
//displays save file dialog
int returnVal = txtOrEncmChooser.showSaveDialog(FileEncryptionFilter.this);
//use chose to save file
if (returnVal == JFileChooser.APPROVE_OPTION)
{
//selects file
File fileName = txtOrEncmChooser.getSelectedFile();
/****The problem is here, how do I figure out what file type the user selected?****/
if .txt is selected{
String filePath = fileName.getPath() + ".txt"; //file path
}
else if .encm is selected
{
String filePath = fileName.getPath() + ".encm"; //file path
}
}
I have searched the forums for solutions, but I only found the solution for opening multiple file types, not saving multiple file types.
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html#getFileFilter()
FileNameExtensionFilter f = (FileNameExtensionFilter) txtOrEncmChooser.getFileFilter();
Since getExtensions() returns an array, you'll have to iterate through all the extensions. If you are sure that it only contains one element, of course, you won't need to do this. Just check f.getExtensions()[0].equals("txt"), for example. You could also create your file filters as local variables and then compare them with the selected one.

fileChooser.setDialogType() Doesn't Work

I have code that is supposed to choose a folder from a JFileChooser, but it still is acting like its choosing a file, even if I use fs.setDialogType. I tried showSaveDialog and showOpenDialog, but they both don't work.
Here is my code:
public static String getFolder() {
JFileChooser fs = new JFileChooser();
fs.setDialogType(JFileChooser.DIRECTORIES_ONLY);
fs.showSaveDialog(null);
if (fs.getSelectedFile() != null)
return fs.getSelectedFile().getAbsolutePath();
return "null";
}
setDialogType is used to set the open, save or custom type for the dialog. Use setFileSelectionMode to specify the whether the dialog should select files or directories
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

JFileChooser - open in current directory

I have a simple JFileChooser set up in the following manner
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(new FileFilter() {
...
});
int v = chooser.showOpenDialog(this);
if (v == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
System.out.println(file.getAbsolutePath());
}
As you can see, this FileChooser starts out in the current directory, which in my Netbeans project, is the root of the project folder. Here's the problem: When I select a file and it prints out the absolute path, it includes the "." in the path. For instance, the output I get is:
/Users/MyName/Folder1/Folder2/./Temp.xls
Of course, this is weird, especially since I'm displaying this to the user. Now, I could be hacky and do some fun post substring processing stuff to get rid of that "/./" portion. But...is there a non-lazy programmer way to fix this problem? Thanks in advance!
Use the system property "user.dir" as follows:
File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);

show file information after choosing in file chooser java

I am exploring Jfilechooser.I already get the file path in the Jfilechooser.Now I want to display the information like file name, file size, location, and access rights.Is their anyway to display those information using the file path only.Anyone can help me?I want it to display in a TextArea.
this is the how I pop up a Jfilechooser.
private void browsebuttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
fieldlocation.setText(filename);
}
Take a look at the JavaDoc for File:
File.getName()
Will return the name of the file
File.length()
Will return the size of the file in bytes
File.getAbsolutePath()
Will return the absolute path of the file
File.canRead()
File.canWrite()
File.canExecute()
Will return your access rights on the file.
One thing I would note about your code is that you don't check the return value from the file chooser. If the user clicks cancel you probably want to abort processing. The way to do this is to check the return value of JFileChoose.showOpenDialog(null); like so:
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Straight from the JavaDoc.
In short I would suggest that you (re)?read the documentation for the APIs you are using. It will save you much time in the long run if you understand your own code.

JFileChooser.showSaveDialog(…) - preserve suggested file name after changing directory

There are already some questions about how to set a default file name for a JFileChooser control.
I'm having a few problems with preserving that default filename when switching directories.
Right now, when I do that, the original filename I supplied get over overwritten by the path of the new directory itself.
Is there anything can be done in order to avoid this behavior?
You could add a PropertyListener to the file chooser, and if you get a "directoryChanged" property, set your default file again.
For example:
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener( new PropertyChangeListener() {
public void propertyChange( PropertyChangeEvent evt )
{
if ( evt.getPropertyName().equals( "directoryChanged" ) )
{
JFileChooser me = (JFileChooser)evt.getSource();
me.setSelectedFile( new File( "text.txt" ) );
}
}
});
It seems like it might do what you want, but is more a workaround than a proper solution.

Categories

Resources