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.
Related
I usually find a workaround for problems, but this time I cannot seem to find one.
I am making a compiler for a self-designed language using JavaCC. Before I simply used System.in to read files, so this way I know my compiler can use any text-based file of any extension.
This project must ONLY open files with a custom extension (.bait). From my research, there are plenty of ways in Java to get a file's extension, but they all require a full path. My compiler is supposed to run from any place in the user's disk through a terminal (CMD), so I do not think Java's options are useful.
The question: How can I filter the file extension of a given file that the compiler rejects the source if it's not .bait?
The original code I use is pretty simple:
hook analizador = new hook (System.in);
analizador.RunLexer();
'hook' being the class and RunLexer() is a method for lexical analysis. The code allows any text-based code to be analyzed. For the extention rule I thought of using *.bait regular expresion as in:
hook analizador = new hook (new FileInputStream("*.bait"));
analizador.codigo();
and
InputStream input = new FileInputStream("*.bait");
hook analizador = new hook (input);
with no luck, so far. Can anybody guide me with this? An explanation of the answer will be gladly appreciated.
EDIT: Thanks to sepp2k and MeetTitan.
System.in was not an option, so instead the filename (used as argument) can be used for all the verifications needed:
String arc = args[0];
if(arc.endsWith(".bait")){ //checks file extention
File src = new File(arc); //created just to use exists()
if(src.exists()){
FileReader fr = new FileReader(arc); //used instead of System.in
hook analizador = new hook(fr);
} else System.out.println("File not found");
} else System.out.println("Invalid filetype");
As for the way to use the program, using terminal (CMD)
java hook file.bait
This code doesn't let the user run .bait files out of the hook directory as intended, so it's safe even if there are several copies of the file in different locations.
Hope it can be of any use to someone, and thank you again, sepp2k and MeetTitan!
Why can't you do something like this?
//this method takes a String and returns a substring containing the characters between the last occurrence of '.' and the end of the String
//For example, getExtension("test/your.file.bait"); will return "bait".
public static String getExtension(String fileNameOrPath) {
return fileNameOrPath.substring(fileNameOrPath.lastIndexOf('.')+1);
}
//this method compares equality of "bait" and the returned extension from our other method
public static boolean isBait(String fileNameOrPath) {
return "bait".equals(getExtension(fileNameOrPath));
}
You can use isBait(String) on any path, relative or absolute, or a filename.
You could also simply leverage String.endsWith(String).
Like so:
public static boolean isBait(String str) {
return str.endsWith(".bait");
}
EDIT
To get a listing of all files in a folder with a specific extension, you'd use a FilenameFilter with File.listFiles()
Like so:
File dir = new File("path/to/folder");
File[] baitFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".bait");
}
});
EDIT to recurse over EVERY subfolder and only get certain files:
public static List<File> recurseGetBait(File dir) { //need method for recursion
List<File> baitFilesList = new ArrayList<>(); //make a new ArrayList that we will populate and return
File[] baitFiles = dir.listFiles(new FilenameFilter() { //get all bait files with previously shown snippet
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".bait");
}
});
for(File baitFile : baitFiles) {
baitFilesList.add(baitFile); //add every file from baitFiles to baitFilesList
}
String[] dirs = file.list(new FilenameFilter() { //get all subfolders of current folder
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
});
for(File dir : dirs) { //iterate over all subfolders
List<File> returned = recursiveGetBait(dir); //run this same method on this subfolder (which will recurse until there are no sub folders)
baitFilesList.addAll(returned); // add all of the previously returned bait files to baitFilesList so we populate and return
}
return baitFilesList; //either returns our list to the previous recurse or returns the fully built list to our original caller
}
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 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);
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
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.