List all files with extension java

Java – Find files with given extension

In this tutorial, we will see how to find all the files with certain extensions in the specified directory.

Program: Searching all files with “.png” extension

In this program, we are searching all “.png” files in the “Documents” directory(folder). I have placed three files Image1.png, Image2.png, Image3.png in the Documents directory.

Similarly, we can search files with the other extensions like “.jpeg”,”jpg”,”.xml”,”.txt” etc.

package com.beginnersbook; import java.io.*; public class FindFilesWithThisExtn < //specify the path (folder) where you want to search files private static final String fileLocation = "/Users/chaitanyasingh/Documents"; //extension you want to search for e.g. .png, .jpeg, .xml etc private static final String searchThisExtn = ".png"; public static void main(String args[]) < FindFilesWithThisExtn obj = new FindFilesWithThisExtn(); obj.listFiles(fileLocation, searchThisExtn); >public void listFiles(String loc, String extn) < SearchFiles files = new SearchFiles(extn); File folder = new File(loc); if(folder.isDirectory()==false)< System.out.println("Folder does not exists: " + fileLocation); return; >String[] list = folder.list(files); if (list.length == 0) < System.out.println("There are no files with " + extn + " Extension"); return; >for (String file : list) < String temp = new StringBuffer(fileLocation).append(File.separator) .append(file).toString(); System.out.println("file : " + temp); >> public class SearchFiles implements FilenameFilter < private String ext; public SearchFiles(String ext) < this.ext = ext; >@Override public boolean accept(File loc, String name) < if(name.lastIndexOf('.')>0) < // get last index for '.' int lastIndex = name.lastIndexOf('.'); // get extension String str = name.substring(lastIndex); // matching extension if(str.equalsIgnoreCase(ext)) < return true; >> return false; > > >
file : /Users/chaitanyasingh/Documents/Image1.png file : /Users/chaitanyasingh/Documents/Image2.png file : /Users/chaitanyasingh/Documents/Image3.png

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Читайте также:  Unable to locate a java runtime that supports javaws

Java: How to list all files in a directory that match a filename extension

I just ran across this Java method I used to create a list of all files in a directory that match a specific filename pattern, or more specifically, matched the same filename extension.

The Java “list files in a directory” source code

First, here’s the source code for this Java “list files” method. I’ll follow this code with a brief description:

Collection getListOfAllConfigFiles(String directoryName)

As you can see, this method takes the name of a directory as input, and then uses the FileUtils.listFiles method, and the WildcardFileFilter class to create a list of all files in the directory that have the same filename extension, in this case, they all end with the extension .cfg .

The Apache Commons IO project

The only magic here is that the FileUtils and WildcardFileFilter classes come from the Apache Commons IO project. When using this method, I have these import statements at the top of my Java class:

import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.WildcardFileFilter;

I’ve found that downloading the Commons IO jar file and using their classes and methods make working with a filesystem, files, and directories, much easier when programming with Java. They have a lot of convenience methods that just make Java filesystem programming easier, including this filename extension / pattern / wildcard example.

Slightly improved Java “list files” method

We can easily improve that method by making it a little more general, and letting the calling program pass in the desired file extension, like this:

Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)

Either way, this is the easiest way I know to use Java to get a list of all files in a directory that match a certain filename pattern, or in this case, all the files that match a filename extension.

Источник

How to get all files with certain extension in a folder in java

endsWith ( ext ) ) ; > > > 1 2 3 4 5 6 7 8 9 10 Finding . zip files in the folder / Users / Arpit / Desktop / Blog — — — — — — — — — File : sampleFile1 . zip File : sampleFile2 . zip File : sampleFile3 . zip File : Spring3 — Quartz — Example . zip File : SpringQuartzIntegrationExample . zip— — — — — — — — — We will use FilenameFilter interface to list the files in a folder, so we will create a inner class which will implement FilenameFilter interface and implement accept method.

How to get all files with certain extension in a folder in java

In this post, we will see how to list all files with certain extension in a folder.
For example, you want to list all .jpg or .zip files in a folder.

We will use FilenameFilter interface to list the files in a folder, so we will create a inner class which will implement FilenameFilter interface and implement accept method. We need to pass created inner class to java.io.File ‘s list method to list all files with specific extension.


Java Program :

So we have found all .zip file in folder “/Users/Arpit/Desktop/Blog”

Was this post helpful?

List All Files in a Directory in Java, Steps to print the files of a directory and its subdirectory are mentioned below. Step 1: Create a File Object for the directory. Step 2: Obtain the array of files and subdirectory of that directory. Step 3: If array [j] is a file, then display the file name and recursively go to the next element of the array [j].

Using File.listFiles with FileNameExtensionFilter

The FileNameExtensionFilter class is intended for Swing to be used in a JFileChooser .

Try using a FilenameFilter instead. For example:

File dir = new File("/users/blah/dirname"); File[] files = dir.listFiles(new FilenameFilter() < public boolean accept(File dir, String name) < return name.toLowerCase().endsWith(".txt"); >>); 

One-liner in java 8 syntax:

pdfTestDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt")); 

Is there a specific reason you want to use FileNameExtensionFilter ? I know this works..

private File[] getNewTextFiles() < return dir.listFiles(new FilenameFilter() < @Override public boolean accept(File dir, String name) < return name.toLowerCase().endsWith(".txt"); >>); > 

List all files from a directory recursively with Java, This is a very simple recursive method to get all files from a given root. It uses the Java 7 NIO Path class. This Function will probably list all the file name and its path from its directory and its subdirectories. Find all files in a directory with extension .txt in Python. 854. How can I open multiple files using … Code sampleCollection files = FileUtils.listFiles(dir,new RegexFileFilter(«^(.*?)»),DirectoryFileFilter.DIRECTORY);Feedback

List all Files from a Directory that match a File Mask (a.k.a Pattern or Glob)

You can use also custom FileVisitor [1], with combination of PathMatcher [2], which works perfectly with GLOBs.

Code might look like this:

public static void main(String[] args) throws IOException < System.out.println(getFiles(Paths.get("/tmp/SOURCE"), "*.doc")); >public static List getFiles(final Path directory, final String glob) throws IOException < final var docFileVisitor = new GlobFileVisitor(glob); Files.walkFileTree(directory, docFileVisitor); return docFileVisitor.getMatchedFiles(); >public static class GlobFileVisitor extends SimpleFileVisitor  < private final PathMatcher pathMatcher; private ListmatchedFiles = new ArrayList<>(); public GlobFileVisitor(final String glob) < this.pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + glob); >@Override public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException < if (pathMatcher.matches(path.getFileName())) < matchedFiles.add(path); >return FileVisitResult.CONTINUE; > public List getMatchedFiles() < return matchedFiles; >> 

I think I might have solved my own question with the insight received here and other questions mentioning the PathMatcher object

final PathMatcher maskMatcher = FileSystems.getDefault() .getPathMatcher("glob:" + mask); final List matchedFiles = Files.walk(path) .collect(Collectors.toList()); final List filesToRemove = new ArrayList<>(matchedFiles.size()); matchedFiles.forEach(foundPath -> < if (!maskMatcher.matches(foundPath.getFileName()) || Files.isDirectory(foundPath)) < filesToRemove.add(foundPath); >>); matchedFiles.removeAll(filesToRemove); 

So basically .getPathMatcher(«glob:» + mask); is the same thing that the DirectoryStream was doing to filter the files

All I have to do now after that is filtering the list of paths that I get with Files.walk by removing the elements that do not match my PathMatcher and are not of type File

It is possible to use common Stream filter to retrieve the filtered file names from Files.walk using String::matches with appropriate regular expression:

final String SOURCE_DIR = "test"; Files.walk(Paths.get(SOURCE_DIR)); .filter(p -> p.getFileName().toString().matches(".*\\.docx?")) .forEach(System.out::println); 
test\level01\level11\test.doc test\level02\test-level2.doc test\t1.doc test\t3.docx 

Input directory structure:

│ t1.doc │ t2.txt │ t3.docx │ t4.bin │ ├───level01 │ │ test.do │ │ │ └───level11 │ test.doc │ └───level02 test-level2.doc 

A recursive solution is possible using newDirectoryStream however it needs to be converted into Stream:

static Stream readFilesByMaskRecursively(Path start, String mask) < List sub = new ArrayList<>(); try < sub.add(StreamSupport.stream( // read files by mask in current dir Files.newDirectoryStream(start, mask).spliterator(), false)); Files.newDirectoryStream(start, (path) ->path.toFile().isDirectory()) .forEach(path -> sub.add(recursive(path, mask))); > catch (IOException ioex) < ioex.printStackTrace(); >return sub.stream().flatMap(s -> s); // convert to Stream > // test readFilesByMaskRecursively(Paths.get(SOURCE_DIR), "*.doc*") .forEach(System.out::println); 
test\t1.doc test\t3.docx test\level01\level11\test.doc test\level02\test-level2.doc 

A prefix **/ may be added to the PathMatcher to cross directory boundaries, then Files.walk -based solution may use simplified filter without the need to remove specific entries:

String mask = "*.doc*"; PathMatcher maskMatcher = FileSystems.getDefault().getPathMatcher("glob:**/" + mask); Files.walk(Paths.get(SOURCE_DIR)) .filter(path -> maskMatcher.matches(path)) .forEach(System.out::println); 

Output (same as in the recursive solution):

test\level01\level11\test.doc test\level02\test-level2.doc test\t1.doc test\t3.docx 

Java — How to list all files within a directory and all its sub, Sorted by: 1. If you can use Java 7 or 8 you could use the FileVisitor, but in Java 7 it means writing more then one line of code. If not and you want to keep it simple, Apache Commons FileUtils may be your friend. Collection files = FileUtils.listFiles (path, new String [] , true); Share.

How to make List with all files in folder using swing?

This example shows how to enumerate the files in a directory and display them in a JToolBar and a JMenu . You can use an Action , such as RecentFile , to encapsulate behavior for use in your ListModel and ListSelectionListener .

You get all the file name from folder with extension and construct a string array out of that.Then use a JList to populate in swing.For example something like below

String options = < "apple.exe", "ball.exe" "cat.exe">; JList optionList = new JList(options); 

See JFileChooser (shameless copy of the JFileChooser help page):

JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG & GIF Images", "jpg", "gif"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(parent); if(returnVal == JFileChooser.APPROVE_OPTION)

setMultiSelectionEnabled (true); is another hint.

How to get all files with certain extension in a folder in, We will use FilenameFilter interface to list the files in a folder, so we will create a inner class which will implement FilenameFilter interface and implement accept method. We need to pass created inner class to java.io.File ‘s list method to list all files with specific extension.

Источник

Оцените статью