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.
Related
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
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)
Right now I'm manually writing song file names into a String array, then sending the strings to InputStream is = this.getClass().getResourceAsStream(filename); to play the song.
I would rather loop through all the song names in my resources folder and load them into the array so that each time I add a song, I don't need to manually type it into the array.
All of my songs are located in resources folder:
Is there a java method or something to grab these names?
The files need to work when I export as .jar.
I thought I could use something like this?
InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/");
Is there a listFiles() or something for that?
Thanks
No, because the classpath is dynamic in Java. Any additional Jar could contribute to a package, a classloader can be as dynamic as imaginable and could even dynamically create classes or resources on demand.
If you have a specific JAR file and you know the path within that JAR file then you could simply treat that file as archive and access it via java.util.jar.JarFile which lets you list all entries in the file.
JarFile jar = new JarFile("res.jar");
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
System.out.println(entry.getName());
}
If you want to do this without knowing the JAR filename and path (e.g. by a class within the JAR itself) you need to get the filename dynamically as Evgeniy suggested; just use your own class name (including package; your screenshot looks like you are in default package, which is a bad idea).
You can try something like this
Enumeration<URL> e = ClassLoader.getSystemResources("org/apache/log4j");
while (e.hasMoreElements()) {
URL u = e.nextElement();
String file = u.getFile();
...
file:/D:/.repository/log4j/log4j/1.2.14/log4j-1.2.14.jar!/org/apache/log4j
extract jar path from here and use JarFile class to know org/apache/log4j contents.
If it is unpacked, you will get straight path and use File.listFIles
I have a folder in which there is a .dat file and one is .zip file ,I have to move the .zip file to another directory
I have two folders one is
1) c:\source folder --> having two files abc.dat and other is abc.zip
2) c:\destination ---> in which zip shpould be get copied
please advise how to achiev this what I have done rite now is ...
File directory = new File(sourceFolder);
File[] listFiles = (mcrpFilePath).listFiles();
for (File f : listFiles) {
if (f.isFile()) { // ?? here logic to pick up the zip file
//logic to move the zip file to other directory
}
}
Use File.renameTo
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
Here is Example
Or you can use Files#move (if you are using java 7)
Move or rename a file to a target file.
here is Example using move()
As simple as using the method renameTo() in File class.
public boolean renameTo(File dest);
Renames the file denoted by this abstract pathname.
Get file full path and rename it to the required location.
And make use of boolean that return by that method,to know weather it's successfully moved or not.
For detecting your zip-file:
if(f.getName.equals("abc.zip"))
or for all zip files:
if(f.getName.endsWith(".zip"))
With a regex:
if(f.getName.matches("abc*\\.zip"))
For moving it:
f.renameTo(new File("C:\dest\abc.zip");
Or, more simply:
new File("C:\src\abc.zip").renameTo("C:\dest\abc.zip");
catching exceptions as needed.
Use java.io.File and its methods to get the list of .zip files and move them (Tutorial - Moving a File or Directory).
import static java.nio.file.StandardCopyOption.*;
...
Files.move(source, target, REPLACE_EXISTING);
SOURCE
The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file