Task :
Write a Java application that accepts two file names as arguments: dirName and fileName Find all non-directory files contained in directory dirName whose name ends in ".java"
I tried to use this code but how can I print out the files ending with ".java" ?
It's the first time I work with this things and I don't know how to use them.
import java.io.File;
import java.io.FilenameFilter;
public class Filter {
public static File[] finder(String dirName){
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename)
{ return filename.endsWith(".txt"); }
});
}
public static void main(String[] args){
String dirName = "src";
System.out.println(finder(dirName));
}
}
return !dir.isDirectory() && filename.endsWith(".java");
Thanks for the help. It works fine now .
import java.io.*;
public class Filter {
public static File[] finder(String dirName) {
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(".java");
}
});
}
public static void main(String[] args) {
String dirName = "src";
File[] files = finder(dirName);
for (File i: files)
System.out.println(i.getName());
}
}
Related
I have a problem, i have this directory with 1k+ files and some folders. I need find the path of the files(which are in subdirectories) that starts with "BCM", but not only the first i find but every single file which start with that.
I tried looking at other answers about this topic but i couldn't find help,
tried using this code:
File dir = new File("K:\\Jgencs");
FilenameFilter filter = new FilenameFilter()
{
public boolean accept (File dir, String name)
{
return name.startsWith("BCM");
}
};
String[] children = dir.list(filter);
if (children == null)
{
System.out.println("No directory found");
}
else
{
for (int i = 0; i< children.length; i++)
{
String filename = children[i];
System.out.println(filename);
File h = new File(dir,filename);
System.out.println(h.getAbsolutePath()
[UPDATED] This is how you can achieve using plain Java and filter text from a variable passing as parameter:
Here is my directory: /tmp
And here is the code running:
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GetAllFilesInDirectory {
public static void main(String[] args) throws IOException {
String filter = "BCM";
List<File> files = listFiles("/tmp", new CustomerFileFilter(filter));
for (File file : files) {
System.out.println("file: " + file.getCanonicalPath());
}
}
private static List<File> listFiles(String directoryName, CustomerFileFilter fileFilter) {
File directory = new File(directoryName);
List<File> files = new ArrayList<>();
// Get all files from a directory.
File[] fList = directory.listFiles(fileFilter);
if(fList != null) {
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
files.addAll(listFiles(file.getAbsolutePath(), fileFilter));
}
}
}
return files;
}
}
class CustomerFileFilter implements FileFilter {
private final String filterStartingWith;
public CustomerFileFilter(String filterStartingWith) {
this.filterStartingWith = filterStartingWith;
}
#Override
public boolean accept(File file) {
return file.isDirectory() || file.isFile() && file.getName().startsWith(filterStartingWith);
}
}
This is the output:
file: /private/tmp/BCM01.txt
file: /private/tmp/BCM01
file: /private/tmp/subfolder1/BCM02.txt
Doing recursive calls to the method when finding a directory to also list the files form inside, and filtering by name the files before adding.
You want Files.walk:
try (Stream<Path> files = Files.walk(Paths.get("K:\\Jgencs"))) {
files.filter(f -> f.getFileName().toString().startsWith("BCM")).forEach(
file -> System.out.println(file));
}
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
}
}
}
I would like to search for files recursively. According to other solutions, I have already done a big portion of the code:
public static File[] getFiles(String path) {
File file = new File(path);
// Get the subdirectories.
String[] directories = file.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
for (String dir : directories) {
// Doing recursion
}
// Get the files inside the directory.
FileFilter fileFilter = new FileFilter();
File[] files = file.listFiles(fileFilter);
return files;
}
FileFilter is just a custom filter of mine. My problem is that I don't know how to do the recursion in this case. Of course I could call getFiles() again for each subdirectory with the subdirectory path as argument but somehow the returning File array must be merged.
Does somebody have a solution?
Use the find() method.
/* Your filter can be initialized however you need... */
YourCustomFilter filter = new YourCustomFilter(extension, maxSize);
try (Stream<Path> s = Files.find(dir, Integer.MAX_VALUE, filter::test)) {
return s.map(Path::toFile).toArray(File[]::new);
}
This assumes your custom filter has a method called test() that accepts the file and its attributes; you'll need to rework your current file filter a bit to accommodate this.
boolean test(Path path, BasicFileAttributes attrs) {
...
}
Working example: http://screencast.com/t/buiyV9UiEa
You can try something like this:
//add this imports
import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public static File[] getFiles(String path) {
File file = new File(path);
// Get the subdirectories.
String[] directories = file.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
//Use a list to save the files returned from the recursive call
List<File> filesList = new ArrayList<File>();
if( directories != null){
for (String dir : directories) {
// Doing recursion
filesList.addAll( Arrays.asList(getFiles(path + File.separator + dir)) );
}
}
// Get the files inside the directory.
FileFilter fileFilter = new FileFilter();
File[] files = file.listFiles(fileFilter);
//Merge the rest of the files with the files
//in the current dir
if( files != null)
filesList.addAll( Arrays.asList(files) );
return filesList.toArray(new File[filesList.size()]);
}
Code tested and working. Hope this helps.
import java.util.Arrays;
import java.util.ArrayList;
Put a fail-safe right after you initialize file (in case of a bad path on the first call).
if (!file.isDirectory()) return new File[0];
And change the last part of your code to:
FileFilter fileFilter = new FileFilter();
ArrayList<File> files = new ArrayList(Arrays.asList(file.listFiles(fileFilter)));
for (String dir : directories) {
files.addAll(Arrays.asList(getFiles(dir)));
}
return files.toArray(new File[0]);
(the toArray method expands the array that you pass to it if it's too small) Ref
You should do something like this:
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public static File[] getFiles(String path) {
File file = new File(path);
String[] directories = file.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
ArrayList<File> files = Arrays.asList(file.listFiles(new FileFilter()));
for (String dir : directories) {
files.addAll(getFiles(dir));
}
return files.toArray(new File[list.size()]);
}
The new File[list.size()] is required because otherwise file.toArray() would return Object[].
Also, you should use a lambda expression instead of FilenameFilter, like so:
String[] directories = file.list((File current, String name) -> {
return new File(current, name).isDirectory();
});
I have a problem with that code:
public class Files {
public static void main(String[] args) throws IOException {
// filter files AAA.txt and BBB.txt from another's
File f = new File("d:\\dir"); // current directory
File f1 = new File("d:\\dir1\\");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.startsWith("A") && name.endsWith(".TXT")) {
//System.out.println(name);
return true;
}
else if (name.startsWith("B") && name.endsWith(".TXT")) {
//System.out.println(name);
return true;
}
else {
//System.out.println(name);
return false;
}
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.getName().startsWith("A") ) {
//here save file to d:\\folder1\\
}
}
}
}
How can I save files with specific name in example AAA.txt to folder1 and BBB.txt to folder 2. Thanks for any examples
From Files class from Java 7:
Use move(Path source, Path target, CopyOption... options)
import static java.nio.file.StandardCopyOption.*;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.Files;
...
for (File file : files) {
if (file.getName().startsWith("A") ) {
//here save file to d:\\folder1\\
// convert file to Path object use toPath() method.
Path targetFilePath = FileSystems.getDefault().getPath("d:\\folder1\\").resolve(file.getFileName())
Files.move(file.toPath(), targetFilePath , REPLACE_EXISTING);
}
}
Is it possible to use a regular expression to get filenames for files matching a given pattern in a directory without having to manually loop through all the files.
You could use File.listFiles(FileFilter):
public static File[] listFilesMatching(File root, String regex) {
if(!root.isDirectory()) {
throw new IllegalArgumentException(root+" is no directory.");
}
final Pattern p = Pattern.compile(regex); // careful: could also throw an exception!
return root.listFiles(new FileFilter(){
#Override
public boolean accept(File file) {
return p.matcher(file.getName()).matches();
}
});
}
EDIT
So, to match files that look like: TXT-20100505-XXXX.trx where XXXX can be any four successive digits, do something like this:
listFilesMatching(new File("/some/path"), "XT-20100505-\\d{4}\\.trx")
EDIT
Starting with Java8 the complete 'return'-part can be written with a lamda-statement:
return root.listFiles((File file) -> p.matcher(file.getName()).matches());
implement FileFilter (just requires that you override the method
public boolean accept(File f)
then, every time that you'll request the list of files, jvm will compare each file against your method. Regex cannot and shouldn't be used as java is a cross platform language and that would cause implications on different systems.
package regularexpression;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularFile {
public static void main(String[] args) {
new RegularFile();
}
public RegularFile() {
String fileName = null;
boolean bName = false;
int iCount = 0;
File dir = new File("C:/regularfolder");
File[] files = dir.listFiles();
System.out.println("List Of Files ::");
for (File f : files) {
fileName = f.getName();
System.out.println(fileName);
Pattern uName = Pattern.compile(".*l.zip.*");
Matcher mUname = uName.matcher(fileName);
bName = mUname.matches();
if (bName) {
iCount++;
}
}
System.out.println("File Count In Folder ::" + iCount);
}
}