JFileChooser to pick a directory or a single file - java

is it possible to make a JFileChooser which can choose a file or a directory?
Because, if I use a filefilter in my chooser it is only possible to choose the files included the filter option, but I am no longer able to choose a directory.
this is my JFileChooser
JFileChooser ch = new JFileChooser();
ch.setAcceptAllFileFilterUsed(false);
ch.setFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f != null && f.isDirectory()) {
return true;
}
if (f == null || !f.getName().toUpperCase().endsWith(".PROPERTIES")) {
return false;
}
return true;
}
public String getDescription() {
return "Property Files" + " (*.properties)";
}
});
ch.setCurrentDirectory(new File("."));
ch.showOpenDialog(this);
if (ch.getSelectedFile() != null) {
ressource = ch.getSelectedFile();
}
else {
return;
}
txtRessource.setText(ressource.getAbsolutePath());

Just call
ch.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
And that way you will be able to select either a file or a directory. This works with combination of your filter.
Btw you don't have to implement the file filter too, there is a FileNameExtensionFilter which does exactly what you want (it also accepts folders):
ch.setFileFilter(new FileNameExtensionFilter("Properties file", "properties"));

To select files and directories try this
file_chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
And to choose only directories try this
dir_chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
REASON
As the name suggests, adding a file filter will only filter out a ceratin types of files and will allow you to choose only particular type of file like .jpg,.png etc if you want to select only image files. But to select a directory or only a file you have to set the file selection mode of the JFileChooser instance. Set the mode according to your requirements.

Dude was looking for the answer of this as well. I think its too late to tell you, but for anyone looking I think adding file.isDirectory() == true on the filter work. So in this case if you are looking to choose files ending with .Properties then
public boolean accept(File f) {
if (f.isDirectory() || f.getName().toUpperCase().endsWith(".PROPERTIES")) {
return true;
}
So in this case if its either a file directory or something that ends with a properties extension

Related

Cannot select folders as directories using JFileChooser

I am currently trying to use JFileChooser to return the path of a file or directory as a string. However, I found that I cannot choose a folder as my selection until I choose a file first. While this isn't a major issue it is by far frustrating to solve.
Gfycat of what is happening: https://gfycat.com/DeadlyDeliriousAzurevase
Code:
public static String openFileChooser()
{
int returnValue = fileChoose.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
fileChoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
return (fileChoose.getSelectedFile().getAbsoluteFile().toString());
}
else
{
return "null";
}
}
Help would be absolutely appreciated, thank you!
You're setting the file selection mode after you've shown the dialog and the user has clicked the button. It won't have any effect at that point. You need to set it before you show the file chooser dialog.
The line you need to move up to be the first line in your method is:
fileChoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
You should change your code to
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(fileChooser.getSelectedFile().getAbsoluteFile().toString());
} else {
System.out.println("Empty");
}
make sure invoke
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
before you open your dialog

How to Search All the Files in a Folder with JFileChooser

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
}
}
}
}
});

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);

Program to check whether extension of a file is .txt

I wrote a java code having an awt text field and a button, where if I click on the button, I can browse a file using JFileChooser. It needs to check whether the file has ".txt" extension or not.I wrote the code below, but it is not getting verified.
Where am I going wrong? Please help to determine where I am wrong.
try{
final JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
chooser.addChoosableFileFilter(new FileFilter() {
public String getDescription() {
return "*.txt";
}
public boolean accept(File filename)
{
if(filename.getName().endsWith(".txt")){
return true;
}
else{
System.out.println("Browsed dest file extension must be .txt");
return false;
}}
});
catch(Exception ex)
{
JOptionPane.showMessageDialog(f,"Exception occurred");
}
Your problem is that:
chooser.showOpenDialog(null);
stop execution of code until user select a file. Add this line after adding FileFilter and eveyrthing should work ok.
Little explanation:
Method showOpenDialog(Component c) blockexecution of current thread until user action and next line of your code will be executed after the user choose a file. If you invoke after adding a FileFilter once again showOpenDialog it will work as you expect.
I would suggest using the #Override annotation for the accept method - see this link #Override explained in Oracle Documentation.
Plus, it would be best to use filename.getName().toLowerCase().endsWith(".txt") instead filename.getName().endsWith(".txt") to ensure that files with the extension .TXT will pass the filter as well.

FileFilter for JFileChooser doesn't filter files - don't why, have code

I want to choose only .csv files with FileChooser but when chooser opens I see all extensions. Do I need to set somehing more then this?
btnFile.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose Value File");
chooser.addChoosableFileFilter(new CSVFilter());
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "
+ chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
}
else {
System.out.println("No Selection ");
}
}
});
and Filter is nested class
class CSVFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File f) {
return f.isFile() || f.getName().toLowerCase().endsWith(".csv");
}
public String getDescription() {
return "*.csv";
}
}
Maybe it should be:
return f.isFile() && f.getName().toLowerCase().endsWith(".csv");
not:
return f.isFile() || f.getName().toLowerCase().endsWith(".csv");
The logic is wrong. It should be
return f.isFile() && f.getName().toLowerCase().endsWith(".csv");
Currently you are accepting any file.
You need a FileFilter for filtering out files from view. ChoosableFileFilter do not hide files from view, just avoid selecting them. Take a look at JFileChooser#setFileFilter(javax.swing.filechooser.FileFilter)
It should be:
#Override
public boolean accept(File f) {
return (f.isFile() && f.getName().toLowerCase().endsWith(".csv")) || f.isDirectory();
}
It respects directories too.
The problem would likely be with this line:
return f.isFile() || f.getName().toLowerCase().endsWith(".csv");
That will return true if the File f is a file, regardless of whether or not it is a .csv file.
You probably want an AND (&&) condition rather than an OR (||) condition. You want to accept any File where it is a file AND it's extension is .csv.
try to do like this:
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".csv");
}
In you CSVFilter you have method called accept, which returns TRUE if the input parameter is file OR csv file.
It will always return TRUE with a valid file parameter.
The condition shoud be
...
if (f.isFile() && f.isCSVFile())
...
You need to actually set the filefilter not just add it as optional filter
chooser.setFileFilter(new CSVFilter());

Categories

Resources