Java search files from folder - java

I am writing a utility that will search the folder and list files.
The main intention is to find all the files with same name but with diff extensions. For eg: in a given folder we have files that are a.log ,a.jpg,a.clone,b.log, c.log,d.log, d.clone and my output should be only c.log and d.log . My main intention is to find the files which contain extension of .clone and do not print them in this case files c and d do not have extension of .clone and they should be the output.
I am not able to list the files with the same name but different extensions.
Any advice on how to go about this.
Regards,
Vilas

When you list all files in some folder, for example: File[] files = file.listFiles(), you can loop through them and check the file names. Here, file is actually the folder in which you want to search for your file.
for(int i=0; i<files.length; i++)
{
if(files[i].getName().startsWith("filename."))
{
do what you want
}
}
So all files that starts with "filename." will meet the criteria, no matter what comes after the . i.e. extension.

Since Java 7 you can use the walkTreeFile() to control how deep you want to go down the tree, and what to do with each file you found (with an appropriate FileVisitor).
With an Executor you can process files without waiting for the search to be finished.

Since Java 8, you should not use FileVisitor, walkTreeFile() and File class as suggested before but you should use the interface Path and the method Files.list(Path dir) :
public static void main(String[] args) throws IOException
{
Path folderWithTheFiles = Paths.get("/my/folder/with/the/files/");
//list the folder and add files names with a .clone extension in a Set
Set<String> cloneFilesNames = Files.list(folderWithTheFiles)
.filter(p->p.toString().endsWith(".clone"))
.map(p -> p.getFileName().toString().split("\\.")[0]).collect(Collectors.toSet());
//list the folder and filter it with the Set created before
Files.list(folderWithTheFiles)
.filter(p->!cloneFilesNames.contains(p.getFileName().toString().split("\\.")[0]))
.map(Path::getFileName).forEach(System.out::println);
}
If you want to search deeper in the files tree use Files.walk(Path dir) instead of Files.list(Path dir)

Related

Processing/Java File Count Issue With File Pathway (Variable Type)

Although the Title isn't very understandable I do have a simple issue. So i'm trying to write some code in a Processing Sketch (https://processing.org/) which can count how many files are in a document. The problem is, is that it doesn't accept the variable type.
File folder = File("My File Path");
folder.listFiles().size;
It says the function File(String) doesn't exist. When I try to put the file path without quation marks, it still doesn't work!
If you have a solution then please use a functioning example so that I know how it works. Thanks for any help!
As Joakim Danielson says it is constructor so you need to use new keyword.
Below code will work for you.
File folder = new File("My File Path");
int fileLength = folder.listFiles().length;
It's a constructor so you need to use new
File folder = new File("My File Path");
//To get the number of files in the folder
folder.listFiles().length;
Assuming the "My File Path" folder is inside your sketch you need to provide the path to your sketch. Luckily Processing already provides a helper function: sketchPath()
Here's an example:
File folder = new File(sketchPath("My File Path"));
println("folder.exists: " + folder.exists());
if(folder.exists()){
println(folder.listFiles().length + " files and/or directories");
}else{
println("folder does not exist, double check the path");
}
Bare in mind there's also a dataPath() function which points to a folder named data in your sketch folder. The data folder is typically used for storing external data (e.g. assets (raster or vector images/Processing font files) or raw data (binary/text/csv/xml/json/etc.)). This is useful to separate your sketch source files from the data to be loaded/accessed by your sketch.
Also, Processing has a few utility functions for listing files and folders.
Be sure to check out Processing > Examples > Topics > File IO > DirectoryList
The example includes less documented functions such as listFiles() (which returns an array of java.io.File objects based on the filters set) or listPaths (which returns an array of String objects: just the paths).
The options and filters are quite handy, for example if you want to list directories only and ignore files you can simply write simply like:
println("directories: " + listFiles(sketchPath("My File Path"),"directories").length);
For example if want to list all the wav files in a data/audio directory inside the sketch you can use:
File[] files = listFiles(dataPath("audio"), "files", "extension=wav");
This will ignore directories and any other file that does not have .wav extension.
To make this answer complete, here are a few more details on the options for listFiles/listPaths from Processing's source code:
"relative" -> no effect with the Files version, but important for listPaths
"recursive"-> traverse nested directories
"extension=js" or "extensions=js|csv|txt" (no dot)
"directories" -> only directories
"files" -> only files
"hidden" -> include hidden files (prefixed with .) disabled by default

Searching Through a Directory

Hello one of the parts of a program i'm working on requires the ability to search through a directory. I understand how using a path variable works and how to get to a directory; but once you are in the directory how can you distinguish files from one another? Can we make an array/or a linked list of the files contained within the directory and search using that?
In this specific program the goal is for the user to input a directory, from there go into sub-directory and find a file that ends with .mp3 and copy that to a new user created directory. It is certain that there will only be one .mp3 file in the folder.
Any help would be very much appreciated.
Seeing what you say, I will suppose that you use the java7 Path api.
To know if a path is a directory or a simple file, use Files.isDirectory(Path)
To list the files / directories in your directory, use Files.list(Path)
The javadoc of the Files class : http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html
If you use the "old" java.io.File api, then you have a listFiles method, which can take a FileFilter as argument to filter, for exemple, only the files ending with ".mp3".
Good luck
Get Files as so:
List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
for (File file : files)
if (file.isFile())
results.add(file.getName());
If you want the extension:
public static String getExtension(String filename){
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0)
extension = fileName.substring(i+1);
return extension;
}
There are other ways to get file extensions listed here but they usually require a common external library.
You can use the File object to represent your directory, and then use the listFiles() (which return an array of files File[]) to retrieve the files into that directory.
If you need to search through subdirectories, you can use listFiles() recursively for each directory you encounter.
As for the file extension, the Apache Commons IO library has a neat FileFilter for that: the SuffixFileFilter.

load a folder from a jar

I am trying to access a directory inside my jar file. I want to go through every of the files inside the directory itself. I tried using the following:
File[] files = new File("ressources").listFiles();
for (File file : files) {
XMLParser parser = new XMLParser(file.getAbsolutePath());
// some work
}
If I test this, it works well. But once I put the contents into the jar, it doesn't because of several reasons. If I use this code, the URL always points outside the jar.
structure of my project :
src
controllers
models
class that containt traitement
views
ressources
See this:
How do I list the files inside a JAR file?
Basically, you just use a ZipInputStream to find a list of files (a .jar is the same as a .zip)
Once you know the names of the files, you can use getClass().getResource(String path) to get the URL to the file.
I presume this jar is on your classpath.
You can list all the files in a directory using the ClassLoader.
First you can get a list of the file names then you can get URLs from the ClassLoader for individual files:
public static void main(String[] args) throws Exception {
final String base = "/path/to/folder/inside/jar";
final List<URL> urls = new LinkedList<>();
try (final Scanner s = new Scanner(MyClass.class.getResourceAsStream(base))) {
while (s.hasNext()) {
urls.add(MyClass.class.getResource(base + "/" + s.nextLine()));
}
}
System.out.println(urls);
}
You can do whatever you want with the URL - either read and InputStream into memory or copy the InputStream into a File on your hard disc.
Note that this definitely works with the URLClassLoader which is the default, if you are using an applet or a custom ClassLoader then this approach may not work.
NB:
You have a typo - its resources not ressources.
You should use reverse domain name notation for your project, this is the convention.

Java and file list

I should get a list of file contained in a directory.
What I do is:
File file = new File(PATH);
for (File index:file.listFiles)
System.out.println(index.toString());
The matter is that doing this I get printed also files I shouldn't see, temporary, for example.
In my test directory I have to file: ciao and test, but when I run my code I see ciao, ciao~, test~, and also other stuff if I modify a file (I suppose they are buffer file).
So, how can I get only true file, as if I was browsing my fileSystem?
If you want to list only files whose attributes (name included) obey a set of conditions, you need to use another version of .listFiles() which takes a FileFilter as an argument. This interface has a sole accept() method which returns true if the file can be listed.
This simple example will filter out files whose name end with a ~:
file.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.getName().endsWith("~");
}
})
If your FileFilter is more complex than the one above, consider exernalizing it to a variable (private static final if the filter will never change).
Files you don't see are probably hidden, you can check that:
File file = ...;
if(file.isHidden()){...}
use
if (!index.isHidden()) {
System.out.println(index.toString());
}
to suppress hidden files.
you further can check for
index.isDirectory()
if you dont want subdirectory to be listed.
But dont expect an method that can read your thougts what you call an real (or clean, or nice) file.
You could write yourself a filter for that, once you now what files to exclude.
See java.io.FileFilter for more.

Recursive method to search through folder tree and find specific file types

So I am writing a code that locates certain information on Protein databases. I know that a recursive folder search is the best possible way to locate these files, but I am very new to this language and have been told to write in Java (I normally do C++)
SO this being said, what method would i use to:
First: Locate the folder on desktop
Second: Open each folder and that folders subfolders
Third: Locate files that end with the ".dat" type (because these are the only files that have stored the Protein information
Thanks for any and all help you can provide
java.io.File is "An abstract representation of file and directory pathnames"
File.listFiles provides a listing of all the files contained within the directory (if the File object represents a directory)
File.listFiles(FileFilter) provides you with the ability to filter a file list based on your needs
So, with that information...
You would specify a path location with something like...
File parent = new File("C:/path/to/where/you/want");
You can check that the File is a directory with...
if (parent.isDirectory()) {
// Take action of the directory
}
You can list the contents of the directory by...
File[] children = parent.listFiles();
// This will return null if the path does not exist it is not a directory...
You can filter the list in a similar way...
File[] children = parent.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() || file.getName().toLowerCase().endsWith(".dat");
}
});
// This will return all the files that are directories or whose file name ends
// with ".dat" (*.dat)
Other useful methods would include (but not limited to)
File.exists to test that the file actually exists
File.isFile, basically instead of saying !File.isDirectory()
File.getName(), returns the name of the file, excluding it's path
File.getPath() returns the path and name of the file. This can be relative, so be careful, see File.getAbsolutePath and File.getCanonicalPath to resolve this.
File.getParentFile which gives you access to the parent folder
Something like this would do the trick:
public static void searchForDatFiles(File root, List<File> datOnly) {
if(root == null || datOnly == null) return; //just for safety
if(root.isDirectory()) {
for(File file : root.listFiles()) {
searchForDatFiles(file, datOnly);
}
} else if(root.isFile() && root.getName().endsWith(".dat")) {
datOnly.add(root);
}
}
After this method returns, the List<File> passed to it will be filled with the .dat files of your directory, and all subdirectories (if i'm not mistaken).
You should have a look at the Java File APIs. In particular you should look at the listFiles method and write FileFilter that selects directories and, of course, the files you're interested into.
A method that will return you all the files matching your criteria (Given that you implement the FileFilter) is this:
List<File> searchForFile(File rootDirectory, FileFilter filter){
List<File> results = new ArrayList<File>();
for(File currentItem : rootDirectory.listFiles(filter){
if(currentItem.isDirectory()){
results.addAll(searchForFile(currentItem), filter)
}
else{
results.add(currentItem);
}
}
return results;
}
use recursive foldr search and use function endsWith() to find the .bat file then you can use any String function to locate your requires information.

Categories

Resources