Description : I am trying to parse my main directory to find all the files of type ".jpg" and my code is able to return all the files that are needed. example "C:\\Ravi\\Sources", in this directory i have mixed files of .xml, .jpg, .gif, now i am also having sub folders inside this directory but i don't know how to modify my code to check for sub-directories as well.
Expertise help is required here :
Code Snippet :
enter code here
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.PrintStream;
public class Subdirectory {
static File f = new File("C:\\Users\\kasharma\\Desktop\\Travelocity R8.3_8.3.0.apk\\res");// File f will represent the folder....
static String[] extensions = new String[]{"png", "jpg", "gif" }; // Declaring array of supported filters...
// Applying filter to identify images based on their extensions...
static FilenameFilter Image_Filter = new FilenameFilter() {
public boolean accept(File f, String name)
{
for(String ext: extensions){
if(name.endsWith("."+ ext)){
return(true);
}
}
return(false);
}
};
public static void goThroughDirectories(String path)
{
}
public static void main(String[] args) {
String path = "C:\\Users\\kasharma\\Desktop\\Travelocity R8.3_8.3.0.apk\\res";
for (File file : f.listFiles(Image_Filter))
{
if (f.isDirectory()) goThroughDirectories(path+f.getName());
BufferedImage img = null;
try {
img = ImageIO.read(file);
System.out.println("image "+ file.getName());
} catch (IOException e) {
// handle errors here
}
}
}
}
Look at java.nio.files
, especially the walkFileTree(...)
and find(...)
methods. Java 8 includes a builtin capability for this.
Using walkFileTree
:
public static void main(String[] args) throws Exception
{
Path p = Paths.get("D:/");
Files.walkFileTree(p,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
System.out.println(file.toFile().getName());
return FileVisitResult.CONTINUE;
}
}
);
}
Here's an even better solution using find
that returns a lazily populated stream and filters for .jpg
at the same time:
public static void main(String[] args) throws Exception
{
Path p = Paths.get("D:/");
Files
.find(
p,
Integer.MAX_VALUE,
(path,attr) -> path.toString().endsWith(".jpg"))
.forEach(path -> System.out.println(path.toFile().getName()));
}
This will give you the idea. This is pseudocode.
void goThroughDirectories(String path)
{
for(File f : fileList)
{
if(f.isDirectory()) goThroughDirectories(path+f.getName());
else {
//do something
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.