Get all file names in directory using JFileChooser? - java

I'm using this bit of code:
fileBrowser() {
String toReturn = null;
JFileChooser Chooser = new JFileChooser();
int choosen = Chooser.showOpenDialog(fileBrowser.this);
if (choosen == JFileChooser.APPROVE_OPTION) {
System.out.println(Chooser.getCurrentDirectory().toString()+"\\"+Chooser.getSelectedFile().getName());
}
}
To get the selected file name and location, which is all working fine. I was wondering as an addition, is there also a way to get all the filenames in that directory as well? something like .getAllFiles() I've had a search around and can't find one?
Thanks in Advance.

Sure, use
File[] filesInDirectory = chooser.getCurrentDirectory().listFiles();
Then you can iterate over that array:
for ( File file : filesInDirectory ) {
System.out.println(file.getName());
}

Well, there's File.list(). This will list all files by their name from the specified directory (i.e. File). But this will also return directory names. In order to circumvent that, use the other File.list(FilenameFilter filter) method that will enable you to filter out directories from the listing.

Related

How to get the actual size of selected files and folders?

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
File selectedFile = fileChooser.getSelectedFile();
long sizeOfDirectory = FileUtils.sizeOfDirectory(selectedFile);
This isn't generating the actual size of selected files and folders, but gives only a value which is less than actual value.
I am selecting more than one folder at once.
How do I fix this issue?
Actually I am selecting 2 folders, then this issue happens
That's because JFileChooser#getSelectedFile will only return ONE. You need to use JFileChooser#getSelectedFiles and loop over them, calling FileUtils.sizeOfDirectory for each file and summing the results
File[] selectedFiles = fileChooser.getSelectedFiles();
long sizeOfDirectory = 0;
for (File file : selectedFiles) {
sizeOfDirectory += FileUtils.sizeOfDirectory(file);
}
(You should also beware that getSelectedFile and getSelectedFiles may return null)

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

How to search for files with a specific extention from a specifically given directory and all subdirectories

Just for my own learning, i am trying to find all mp3 files in my music collection and finding all the tracks which do not have id3v2 tags. My code gives me information about the directory i specify, but it doesn't look for the mp3 files in subdirectories. Although i can see that it recognises the directories as i can print them out. Please see my code below. I am very sorry if the formatting of the code is not correct. I am blind and using a screen reader and the formatter on this site is not very accessible to me.
public static int numberOfUntaggedTracks(String directory) throws UnsupportedTagException, InvalidDataException, IOException {
int untaggedTracks = 0;
File f = new File(directory);
File l[] = f.listFiles();
for (File x: l) {
if (x.isHidden() || !x.canRead())
continue;
if (x.isDirectory()) {
System.out.println("testing" + x.getPath());
numberOfUntaggedTracks(x.getPath());
} else if (x.getName().endsWith(".mp3")) {
Mp3File song = new Mp3File(x.getPath());
if (song.hasId3v1Tag() == false) {
untaggedTracks++;
}
//end of else if checking for .mp3 extension
}
//end of for loop
}
return untaggedTracks;
}
FileUtils from apatche commons-io has a listFiles method that should do what you need.
The method takes two IOFileFilter instances that you can use to filter files (mp3 files in your case) and to filter sub directories (so you can control which directories to include in your search).
To make your code work just change numberOfUntaggedTracks(x.getPath()); to untaggedTracks += numberOfUntaggedTracks(x.getPath());

Java searching file name from the one folder

I am studying Java and I am not really sure the way to searching file. I would like to build the function which returning file names ( the files name should begin with star and end with .txt)
For example, in the folder we have Java source file with some file. For example, files:
1.txt
2.txt
4.txt
start.txt
star.txt
onstart.txt
starton.txt
myjava.java
Then I would like to get the start.txt, star.txt & starton.txt
I was looking for the FilenameFilter but I wasn't able to find to good way to find file. Does any one know the way to find files?
Probably the easiest way is to simple use File#listFiles(FileFilter), something like
File[] fileList = new File("/path/to/search").listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
});
// You'll need this import: import java.io.File;
File folder = new File("C:/Folder_Location");
// gets you the list of files at this folder
File[] listOfFiles = folder.listFiles();
// loop through each of the files looking for filenames that match
for(int i = 0; i < listOfFile.length; i++){
String filename = listOfFiles[i].getName();
if(filename.startsWith("Stuff") && listOfFiles[i].getName().endsWith("OtherStuff")){
// do something with the filename
}
}
File#getName() should return aString`, then use:
filename.startsWith(...);
filename.endsWith(...);

Get file case-sensitive name, with case-insensitive spelling

I am making an application where the user picks a file from:
FilePicker.PickFile(filename)
where filename is a string.
In the method, it will translate into:
File file = new File(filename);
and nothing is wrong with that. Next, I do,
if(file.exists()){
System.out.println(file.getName());
}
else{
System.out.println("Fail.");
}
and this is where the problem begins. I want to get the name of the file, say "HELLO.txt," but if filename is "hello.txt," it still passes the file.exists() check, and file.getName() returns as "hello.txt," not "HELLO.txt". Is there a way, to return file.getName() as the case-sensitive version as "HELLO.txt?" Thanks!
An example:
HELLO.txt is the real file
FilePicker.PickFile("hello.txt");
OUTPUT:
hello.txt
When you are using Windows, which is case preserving (FAT32/NTFS/..), you can use file.getCanonicalFile().getName() to get the canonical name of the selected file.
When you are using Linux or Android and you want to select a file based on a file name that does not necessarily match case, iterate through all files in the file's directory (file.getParent()), and pick the one that .equalsIgnoreCase the filename. Or see Case-insensitive File.equals on case-sensitive file system
/**
* Maps lower case strings to their case insensitive File
*/
private static final Map<String, File> insensitiveFileHandlerCache = new HashMap<String, File>();
/**
* Case insensitive file handler. Cannot return <code>null</code>
*/
public static File newFile(String path) {
if (path == null)
return new File(path);
path = path.toLowerCase();
// First see if it is cached
if (insensitiveFileHandlerCache.containsKey(path)) {
return insensitiveFileHandlerCache.get(path);
} else {
// If it is not cached, cache it (the path is lower case)
File file = new File(path);
insensitiveFileHandlerCache.put(path, file);
// If the file does not exist, look for the real path
if (!file.exists()) {
// get the directory
String parentPath = file.getParent();
if (parentPath == null) {
// No parent directory? -> Just return the file since we can't find the real path
return file;
}
// Find the real path of the parent directory recursively
File dir = Util.newFile(parentPath);
File[] files = dir.listFiles();
if (files == null) {
// If it is not a directory
insensitiveFileHandlerCache.put(path, file);
return file;
}
// Loop through the directory and put everything you find into the cache
for (File otherFile : files) {
// the path of our file will be updated at this point
insensitiveFileHandlerCache.put(otherFile.getPath().toLowerCase(), otherFile);
}
// if you found what was needed, return it
if (insensitiveFileHandlerCache.containsKey(path)) {
return insensitiveFileHandlerCache.get(path);
}
}
// Did not find it? Return the file with the original path
return file;
}
}
Use
File file = newFile(path);
instead of
File file = new File(path);
It's backed by a cache so it shouldn't be too slow. Did a few test runs and it seems to work. It recursively checks the the parent directories to see if they do have the correct letter cases. Then it lists for each directory all files and caches their correct letter casing. In the end it checks if the file with the path has been found and returns the file with the case sensitive path.
Looks like in Java 7 and above on Windows, you can use Path#toRealPath(NOFOLLOW_LINKS) and it would be more correct than getCanonicalFile() in the presence of symlinks.

Categories

Resources