I have small problem with textfilter. Here's my code:
File f = new File("c:\\dir\\");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.toLowerCase().startsWith("a")
&& name.toLowerCase().endsWith(".txt")) {
return true;
} else if ((name.toLowerCase().startsWith("b") && name
.toLowerCase().endsWith(".txt"))) {
return true;
} else {
return false;
}
}
};
File[] files = f.listFiles(textFilter);
Now the order in "files" array look's like:
A B
How can I change the order of "files" array that could look's like:
B A
Why I must do that? Becaues I need first read file "B" over the file "A". Could somebody write me any sugestions? Thanks.
The solution is:
Arrays.sort(files, Collections.reverseOrder());
Thanks #Gofoboso
Related
i have a folder with two files: one pdf and one xml.
When i click on folder i want get path of xml file only.
With my code(that i post below) i get paths of both files.
Who can help me?
THANKS!
private ArrayList<String> GetFiles2(File f) {
ArrayList<String> MyFiles = new ArrayList<String>();
//File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getPath());
}
System.out.println("MYFILE:"+MyFiles);
return MyFiles;
}
my result : MYFILE:
`[/storage/emulated/0/ordinazioni/2/23_Agosto_2017_09_44_51_AM.xml,` /storage/emulated/0/ordinazioni/2/23_Agosto_2017_09_44_51_AM.pdf]
You can use the overriden version of File#listFiles(FileFilter) to get specific files from a directory.
File[] files = f.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".xml");
}
});
Full implementation :
private ArrayList<String> getXmlFiles(File directory) {
ArrayList<String> names = new ArrayList<>();
directory.mkdirs();
File[] files = directory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".xml");
}
});
for(File f : files)
names.add(f.getPath());
System.out.println("MYFILE:" + names);
return files.length > 0 ? names : null;
}
Anyway I recommend you to return an empty list insteand of null to avoid NPE issues (Just return names)
You can change your for-loop like this for example:
for (int i=0; i<files.length; i++) {
if(files[i].getPath().endsWith(".xml")) {
MyFiles.add(files[i].getPath());
}
}
this will add to the MyFiles list only the paths of the xml files in the praticular folder
For getting a specific file location use this code,
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
eg ;
"/AAlist/"+serialno.get(position).trim()+".jpg"
I need to find a file name from the list of filenames and to initiate two methods according to the found result. I tried:
FileList result = service.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
Boolean found = files.contains("XYZ");
if(found)
{
insertIntoFolder();
} else {
createFolder();
}
}
}
I need to find XYZ (the filename) from a list of file names (like sjh, jsdhf, XYZ, ASDF). Once I've found it I need to stop the search. If the name doesn't match the list of names I need to create a folder only once after checking all names from that list.
Boolean found = files.contains("XYZ");
This line is problematic. files is a list of File objects, none of which will match the String "XYX". List.contains() essentially calls Object.equals() on every element of the list, and File.equals("XYZ") will always return false.
If you're programming in an IDE like Eclipse it should show a warning on this line, since it's a bug that can be detected at compile-time.
To determine if a File in a List<File> has a filename matching a given string you need to operate on the filename itself, so the above line should instead be:
boolean found = file.getName().equals("XYZ");
Depending on what exactly you're trying to match you might want to use .getName(), .getAbsolutePath(), or .toString().
It's also a good idea to use the Path API introduced in Java 7, rather than File, which is essentially a legacy class at this point.
If you want a more elegant solution than manually looping over files looking for a match you can use Files.newDirectoryStream(Path, Filter) which allows you to define a Filter predicate that only matches certain files, e.g.
Files.newDirectoryStream(myDirectory, p -> p.getFileName().toString().equals("XYZ"))
File.list(FilenameFilter) is a similar feature for working with File objects, but again, prefer to use the Path API if possible.
Here is a example:
/**
* return true if file is in filesList else return false
*/
static boolean isFileInList(File file, List<File> filesList) {
for(File f: filesList) {
if (f.equals(file)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
List<File> files;// the filelist; make sure assign these two variable.
File file; // the file you want to test.
if (isFileInList(file, files)) {
//file is presented
} else {
//file is not presented
createFolder();
}
}
package test;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class DirectoryContents {
public static void main(String[] args) throws IOException {
File f = new File("."); // current directory
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt")) {
return true;
} else {
return false;
}
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
}
am trying to compare all the values in my arraylist with all the files in my c:drive
but the code below does not work
List<String> list = new ArrayList<String>();
list.add("*.txt,*.docx");
File file = new File("c:\\*.txt");
if (file.equals(list)) {
System.out.println("file was found");
}else{System.out.println("nothing was found");
}
so the idea is that anytime i run my the code my arraylist would compare itself with my c: drive and list all files that has the extension of "docx and txt" out.
i realised that when i use wildcards it didn't work.
What you need is a FileNameFilter to get all files that pertain to your requirements
Here is an example of getting all *.txt files from current directory. You can implement FileNameFilter to create your own filter that will work on your List.
File f = new File("."); // current directory
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt")) {
return true;
} else {
return false;
}
}
};
File[] files = f.listFiles(textFilter);
Hope this helps.
I want to list and print them out my src folder. But program is listing all files like .bin .classpat .project. I want to list and print only .ncat extension files. How can i do that ?
File f = null;
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths){
System.out.println(path);
}
}catch(Exception e){
e.printStackTrace();
}
You can define a FileNameFilter :
String[] list = dir.list(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return name.endsWith("suffix");
}
});
Easy way would be to check if the path ends with the extension as follows:
File f = null;
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths){
if(path.toLowerCase().endsWith(".ncat")){
System.out.println(path);
}
}
}catch(Exception e){
e.printStackTrace();
}
Welcome to Stack Overflow.
Take a look at the String.endsWith(String suffix) method (see
here)
and make use of an if-condition.
Update
There is a better solution to this problem. Because this is a homework question (as the questioner mentioned) I will continue to elaborate the obvious way. One may google for FileFilter if he is required to use the "more professional" way.
Moving on: You are iterating over all files that are "stored" inside your paths variable (the for-loop). Inside the loop you are currently printing every file name. What you want to do, is to check if a file ends with the desired extension. If this condition is true, you can print it. If not: don't do anything.
try this
public void filter(){
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return name.endsWith("txt");
}
});
for(String path:paths){
System.out.println(path);
}
}catch(Exception e){
e.printStackTrace();
}
}
Before debugging the late-hour-out-of-bound-recursive-function: is there a command to get subdirs? giveMeSubDirs(downToPath)?
// WARNING: RECURSION out of bound or too much data
public HashSet<FileObject> getAllDirs(String path) {
HashSet<FileObject> checkedDirs = new HashSet<FileObject>();
HashSet<FileObject> allDirs = new HashSet<FileObject>();
String startingPath = path;
File fileThing = new File(path);
FileObject fileObject = new FileObject(fileThing);
for (FileObject dir : getDirsInDir(path)) {
// SUBDIR
while ( !checkedDirs.contains(dir)
&& !(getDirsInDir(dir.getFile().getParent()).size() == 0)) {
// DO NOT CHECK TOP DIRS if any bottom dir UNCHECKED!
while ( uncheckedDirsOnLevel(path, checkedDirs).size() > 0) {
while (getDirsInDir(path).size() == 0
|| (numberOfCheckedDirsOnLevel(path, checkedDirs)==getDirsInDir(path).size())) {
allDirs.add(new FileObject(new File(path)));
checkedDirs.add(new FileObject(new File(path)));
if(traverseDownOneLevel(path) == startingPath )
return allDirs;
//get nearer to the root
path = traverseDownOneLevel(path);
}
path = giveAnUncheckedDir(path, checkedDirs);
if ( path == "NoUnchecked.") {
checkedDirs.add(new FileObject( (new File(path)).getParentFile() ));
break;
}
}
}
}
return allDirs;
}
Summary about the code:
Go as deep to the directory tree as possible. When there is no dir in a dir, stop, put the dir to the set, traverse up. Do not check dirs in the set.
Stop and return the set if you reach the starting path.
Repeat steps 1 and 2.
PREMISE: the directory-structure is finite and with a small data amount.
You can get all subdirs with the following snippet:
File file = new File("path");
File[] subdirs = file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
});
This gets only immediate subdirs, to retrieve all of them recursively you could write:
List<File> getSubdirs(File file) {
List<File> subdirs = Arrays.asList(file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
}));
subdirs = new ArrayList<File>(subdirs);
List<File> deepSubdirs = new ArrayList<File>();
for(File subdir : subdirs) {
deepSubdirs.addAll(getSubdirs(subdir));
}
subdirs.addAll(deepSubdirs);
return subdirs;
}
No, there is no such functionality in the Java standard API. But there is in Apache commons-io; if you don't want to include it as a library, you could also look at the source code.
Another version with no recursion, and alphabetical order. Also uses a Set to avoid loops (a problem in Unix systems with links).
public static Set<File> subdirs(File d) throws IOException {
TreeSet<File> closed = new TreeSet<File>(new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
return f1.toString().compareTo(f2.toString());
}
});
Deque<File> open = new ArrayDeque<File>();
open.push(d);
closed.add(d);
while ( ! open.isEmpty()) {
d = open.pop();
for (File f : d.listFiles()) {
if (f.isDirectory() && ! closed.contains(f)) {
open.push(f);
closed.add(f);
}
}
}
return closed;
}
The sample code above is missing ");" at the end of the statement.
The correct code should be:
File file = new File("path");
File[] subdirs = file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}
});
Using recursion:
private void getAllSubFoldersInPath(File path)
{
File[] files=path.listFiles();
try {
for(File file: files)
{
if(file.isDirectory())
{
System.out.println("DIRECTORY:"+file.getCanonicalPath());
getAllSubFoldersInPath(file);
}
else
{
System.out.println("FILE: "+file.getCanonicalPath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is an improved code with Java 8 approach. This code will run on a Recursion basis and find the directories until the last root.
List<File> findAllSubdirs(File file) {
List<File> subdirs = Arrays.asList(file.listFiles(File::isDirectory));
subdirs = new ArrayList<File>(subdirs);
List<File> deepSubdirs = new ArrayList<File>();
for(File subdir : subdirs) {
deepSubdirs.addAll(findAllSubdirs(subdir));
}
subdirs.addAll(deepSubdirs);
return subdirs;
}
If you want only immediate subdirectories list, try with the below line of code..
List<File> subdirs = Arrays.asList(file.listFiles(File::isDirectory));
Get all files from root file as array (#see listFiles)
Sort just for directories by distinguishing between files & directories (#see isDirectory)
Convert (filtered) array from step 1 & 2 to list
Add all found directories to resulting list
Repeat that pattern for each directory file you found in step 1, with growing resulting list
At the end, return resulting list
All that put into some lambda magic:
private static List<File> getAllSubDirectories(File root, List<File> result) {
List<File> currentSubDirs = Arrays.asList(Objects.requireNonNull(root.listFiles(File::isDirectory), "Root file has to be directory"));
result.addAll(currentSubDirs);
currentSubDirs.forEach(file -> getAllSubDirectories(file, result));
return result;
}
Just start with root file (which should be a directory) and an empty list.
Note: Step 1 & 2 can be combined with a filter (#see listFiles(FileFilter filter))
class DirFileFilter extends FileFilter {
boolean accept(File pathname) {
return pathname.isDirectory();
}
}
DirFileFilter filter = new DirFileFilter();
HashSet<File> files = new HashSet<File>();
void rec(File root) {
// add itself to the list
files.put(root);
File[] subdirs = root.list(filter);
// bound of recursion: must return
if (subdirs.length == 0)
return;
else //this is the recursive case: can call itself
for (File file : subdirs)
rec(file);
}