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);
Related
In my Java program there is a part where the user can choose and change the working directory. The problem is that there is no action performed, when I click on 'choose' after choosing the directory path. The choosing window just stays opened.
However, when I do enter any text in the field "File Name" or choose any file in the directory and do click 'choose' the window is being closed and the directory is chosen.
My code is very simple and I really don't understand why it's not working. You can find my code here:
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(returnVal == JFileChooser.APPROVE_OPTION) {
stringHomeDir = chooser.getCurrentDirectory().getPath();
}
...
How can I change it so the user can easily choose a directory in the file chooser?
int returnVal = chooser.showOpenDialog(null);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
The order of these two statements should be reversed, since the showOpenDilaog method blocks until it closes.
Change the order of statements and use setSelectedFile(File) method of JFileChooser class.
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setSelectedFile(new File(chooser.getCurrentDirectory() + "/" + "Downloads")));
int returnVal = chooser.showOpenDialog(null);
...
'MyDocuments' is a default current directory of JFileChooser and 'Downloads' is a subdirectory of 'MyDocuments'.
I have a program that (so far) searches through a file for certain keywords and prints all the lines that have that keyword in it. The problem is it can only search one text file at a time. How can I make it so it searches every text file inside of a folder?
This is the code for the Find File Button that opens just a text file
findFileButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChoice = new JFileChooser();
fileChoice.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = fileChoice.showOpenDialog(AdminPanel.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fileChoice.getSelectedFile();
wantedFile = file.getAbsolutePath();
}
}
});
I tried switching the fileSelectionMode to FILES_AND_DIRECTORIES but when i clicked on a folder it would trigger my try/catch for a file wasn't found/specified.
Any help?
Thanks,
~Zmyth
To start with, when using FILES_AND_DIRECTORIES, you will either get a file OR directory. You need to check the type using File.isDirectory to determine what you should do. If it's a directory, then you need to list all the files within it and process them as required, if it's a file, you just need to process it as normal.
If you only want the user to be able to select directories, you could use DIRECTORIES_ONLY
To search the directory...
You could...
Use one of the File#listFiles methods to list all the files from within the selected directory.
This will only list the files for the current directory, if you want to do a recursive search, you need to implement this yourself, but's not to hard
You could...
Use Files#walkFileTree which can be used to walk the current directory and sub directories, depending how you code the FileVisitor
See Walking the File Tree for more details
Sorry if I was unclear in my original question, I wasn't sure how to go about searching for the files in a folder instead of just a file. I was able to get it eventually though with the help of the one answer. I would up vote it but I don't have enough reputation yet. This is what I was looking for:
findFileButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChoice = new JFileChooser();
fileChoice.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fileChoice.showOpenDialog(Panel.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File folder = fileChoice.getCurrentDirectory();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
wantedFilesList.add(listOfFiles[i].getAbsolutePath());
currentFilesList.add(listOfFiles[i].getName());
}
else if (listOfFiles[i].isDirectory())
{
// Blerg
}
}
}
}
});
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.
I want to make a list with filename from a folder and show all the files that are present in that folder with a particular extension. I want the list to be selectable so that I can select and delete the file from the list or edit it. I know how to select all files from a folder but don't know how to show it in GUI.
File folder = new File("c:/");
File[] listOfFiles = folder.listFiles();
This example shows how to enumerate the files in a directory and display them in a JToolBar and a JMenu. You can use an Action, such as RecentFile, to encapsulate behavior for use in your ListModel and ListSelectionListener.
You get all the file name from folder with extension and construct a string
array out of that.Then use a JList to populate in swing.For example something
like below
String options = { "apple.exe", "ball.exe" "cat.exe"};
JList optionList = new JList(options);
Hope this will help you.
See JFileChooser (shameless copy of the JFileChooser help page):
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
See the FilenameFilter?
setMultiSelectionEnabled (true); is another hint.
Location: java/docs/api/javax/swing/JFileChooser.html
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.