Select files with similar names - java

I'm searching for a script that allow to select multiple files with similar name.
I've got 10 files:
hello.myapp-1.apk
hello.myapp-2.apk
hello.myapp-3.apk
hello.myapp-4.apk
other.ot
...
...
...
...
10....
i want select the files from hello.myapp-1.apk to hello.myapp-4.apk. Is possible to do with only one line of code like this ?
File su6 = new File("/dir/app/hello.myapp-*.apk");

File dir = new File("/dir/app/");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith("hello.myapp-") && name.endsWith(".apk");
}
});
for (File file : files) {
//do stuff with file
}

You can do something like this:
File[] result = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("hello.myapp-");//or use contains, regex/matcher etc
}
});

for (int i=0; i<5; i++)
File su6 = new File("/dir/app/hello.myapp-" + i + ".apk");

Related

Search for file of a specific pattern in a directory

In Java, how do I check folders recursively for a file of a specific pattern? I've seen the below code in a lot of posts online:
public static void findFiles() throws IOException {
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
}
In my application, I basically need to check files matching *.txt in a user's home directory.
Since the path will vary for each user, how do I use this code to search for a file matching a pattern anywhere on the filesystem?
You could actually simply use:
final File dir = new File(System.getProperty("user.home"));
This would set the dir to your user's home directory. From there, you simply have to list all the .txt files, not recursively ;)
However, if you still want to list all files from a directory, recursively, you can use the following method:
public static List<File> walk(final File root, final String extension) {
final File[] list = root.listFiles();
if (list == null) {
return Collections.EMPTY_LIST;
}
final List<File> res = new ArrayList<>();
for (final File f : list) {
if (f.isDirectory()) {
res.addAll(walk(f, extension));
} else {
if (f.getName().endsWith(extension)) {
res.add(f);
}
}
}
return res;
}
You can use it as follows:
public static void main(final String[] args) {
for (final File file : walk(new File("/home/user3751169"), ".txt")) {
System.out.println(file.getAbsolutePath());
}
}
On the other hand, if you want to look only for the files in the home directory of the current user, you should remove the recursive call to walk():
public static List<File> walk(final File root, final String extension) {
final File[] list = root.listFiles();
if (list == null) {
return Collections.EMPTY_LIST;
}
final List<File> res = new ArrayList<>();
for (final File f : list) {
if (f.isFile() && f.getName().endsWith(extension)) {
res.add(f);
}
}
return res;
}

How to return File[] array after adding all files to it

I am new to this group. Please suggest how to return File[] array as my code below is giving NullPointerException when I am trying to add all text files from "D:\" to File[] array, as I want to return all text files as an File[] array which will be used in another method to read all text files.
File[] allFiles;
int i = 0;
public File[] findFiles(File source) {
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if (!pathname.isHidden()) {
return true;
}
return false;
}
};
File[] list = source.listFiles(filter);
if (list != null) {
for (File f : list) {
if (f.isDirectory()) {
findFiles(f);
}
if (f.getName().contains("txt")) {
System.out.println(f.getAbsolutePath());
allFiles[i] = f; // it is giving nullpointerexception
i++;
}
}
}
return allFiles; // want to return this to another method
}
The main problem you're having is you've not initialized allFiles before using it...
File[] list = source.listFiles(filter);
if (list != null) {
for (File f : list) {
//...
// still null
allFiles[i] = f; // it is giving nullpointerexception
You could use allFiles = new File[list.length], but the problem here is you could end up with null elements in the list, as you are filtering out elements...
Instead, you could use your FileFilter, that's what it's there for...for example...
public File[] findFiles(File source) {
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.isHidden() &&
pathname.getName().toLowerCase().endsWith(".txt");
}
};
File[] list = source.listFiles(filter);
return list;
}
Basically, what this does is checks to see if the file is not hidden and if its name ends with .txt, as an example...
Updated
Because you're doing a recursive look up, you really need some way to add new files to your array and grow it dynamically.
While you can do this with plain old arrays, some kind of List would be much easier, for example...
The following uses the FileFilter to find all non-hidden files that directories or end in .txt
It then sorts the resulting list of files, so that the "files" appear first and the "directories" or sorted to the bottom, this is a nit pick, but ensure a certain order of files in the list.
It then processes the file list, adding the "files" to the List and recurisivly scanning the "directories", adding the results to the List...
public static File[] findFiles(File source) {
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.isHidden() &&
(pathname.isDirectory() ||
pathname.getName().toLowerCase().endsWith(".txt"));
}
};
File[] files = source.listFiles(filter);
Arrays.sort(files, new Comparator<File>() {
#Override
public int compare(File o1, File o2) {
int compare = 0;
if (o1.isDirectory() && o2.isDirectory()) {
compare = 0;
} else if (o1.isFile()) {
compare = -1;
} else {
compare = 1;
}
return compare;
}
});
List<File> fileList = new ArrayList<>(25);
for (File file : files) {
if (file.isFile()) {
fileList.add(file);
} else {
fileList.addAll(Arrays.asList(findFiles(file)));
}
}
return fileList.toArray(new File[fileList.size()]);
}
As an example...
Very simple, just initialize the allFiles array
File[] list = source.listFiles(filter);
// initialize here because we know the size now.
allFiles = new File[list.length];
Define the File[] allFiles,Like -
File[] allFiles = new File[list.length];
Alternatively you can use List instead of Array, which is dynamic array(not fixed size).
Initialization -
List<File> allFiles = new ArrayList<File>();
Adding element -
allFiles.add(f);
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.isHidden() &&
pathname.getName().toLowerCase().endsWith(".txt");
}
};
File[] files = f.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("is a directory");
} else {
System.out.print("is a file");
}
System.out.println(file.getCanonicalPath());
}

Java get Files in Folder?

im trying to get the files in a dictonary including the type
like:
src/mime.txt
src/pic1.png
String path = "dic images/";
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
uploadFile(path + "" + listOfFiles[i].getName());
}
}
This didnt work cause with listOfFiles[i].getName() i get only the "pic1" withou the type or?
use getAbsolutePath instead of getName
Try this:
File folder = new File("your path");//for example D:/java
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
if (listOfFiles[i].isFile()) {
System.out.println(listOfFiles[i].getAbsolutePath());
}
One step further, if you need to print the full name of all the files in the subfolders too, try this:
public static void main(String[] args){//or whatever to call the printFiles for the first time
File folder = new File("D:/java");
printFiles(folder);
}
static void printFiles(File folder) {
File[] listOfFiles = folder.listFiles();
for (File f : listOfFiles) {
if (f.isFile()) {
System.out.println(f.getAbsolutePath());
}
else
printFiles(f);
}
}
Using NIO.2 you can do this:
public void findAllFilesInDirectory(Path pathToDir) throws IOException {
Files.walkFileTree(pathToDir, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (Files.isRegularFile(file)) {
System.out.println(file.toString());
}
return FileVisitResult.CONTINUE;
}
});
}
This print paths to all regular files in choosen directory. It also prints regular files from subdirectories.
Documentation:
http://docs.oracle.com/javase/tutorial/essential/io/walk.html

Retrieve all XML file names from a directory using JAVA

I have a directory with multiple files. I need to retrieve only XML file names in a List using Java. How can I accomplish this?
Try this, {FilePath} is directory path:
public static void main(String[] args) {
File folder = new File("{FilePath}");
File[] listOfFiles = folder.listFiles();
for(int i = 0; i < listOfFiles.length; i++){
String filename = listOfFiles[i].getName();
if(filename.endsWith(".xml")||filename.endsWith(".XML")) {
System.out.println(filename);
}
}
}
You can use also a FilenameFilter:
import java.io.File;
import java.io.FilenameFilter;
public class FileDemo implements FilenameFilter {
String str;
// constructor takes string argument
public FileDemo(String ext) {
str = "." + ext;
}
// main method
public static void main(String[] args) {
File f = null;
String[] paths;
try {
// create new file
f = new File("c:/test");
// create new filter
FilenameFilter filter = new FileDemo("xml");
// array of files and directory
paths = f.list(filter);
// for each name in the path array
for (String path : paths) {
// prints filename and directory name
System.out.println(path);
}
} catch (Exception e) {
// if any error occurs
e.printStackTrace();
}
}
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(str.toLowerCase());
}
}
You can filter by using File.filter(FileNameFilter). Provide your implementation for FileNameFilter
File f = new File("C:\\");
if (f.isDirectory()){
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
if(name.endsWith(".xml")){
return true;
}
return false;
}
};
if (f.list(filter).length > 0){
/* Do Something */
}
}

Select a particular type of file in java

I am selecting files in java using the following code:
File folder = new File("path to folder");
File[] listOfFiles = folder.listFiles();
Now what to do if I want to select only image files?
Use one of the versions of File.listFiles() that accepts a FileFilter or FilenameFilter to define the matching criteria.
For example:
File[] files = folder.listFiles(
new FilenameFilter()
{
public boolean accept(final File a_directory,
final String a_name)
{
return a_name.endsWith(".jpg");
// Or could use a regular expression:
//
// return a_name.toLowerCase().matches(".*\\.(gif|jpg|png)$");
//
};
});
You can use File.listFiles() with a FilenameFilter using ImageIO.getReaderFileSuffixes
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
List<String> images = Arrays.asList(ImageIO.getReaderFileSuffixes());
String extension = "";
int i = name.lastIndexOf('.');
if (i > 0) {
extension = name.substring(i+1);
}
return images.contains(extension.toLowerCase());
}
});
May this code help you
String imageExtension[] = new String[]{
"jpg", "png", "bmp" // add more
};
File direcory = new File("path");
File[] listFiles = direcory.listFiles();
ArrayList<File> imageFileList = new ArrayList();
for(File aFile : listFiles ) {
// use FilenameUtils.getExtension from Apache Commons IO
String extension = FilenameUtils.getExtension(aFile.getAbsolutePath());
for(String ext: imageExtension) {
if(extension.equals(ext)) {
imageFileList.add(aFile);
break;
}
}
}

Categories

Resources