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"
Related
When I try to list files in a folder with this:
String file;
File folder = new File("/Users/francesco/Desktop/VIDEOS");
File[] listOfFiles = folder.listFiles();
BufferedReader br = null;
for (int i = 0; i < listOfFiles.length; i++){
It reads also the .DS_Store file inside the folder, giving me a lot of errors. How can I avoid to read these .DS_Store files in Java?
You can pass a FileNameFilter to File.listFiles to filter out the one you don't want.
File[] files = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return !name.equals(".DS_Store");
}
});
EDIT: Java 8 lambda version
File[] files = folder.listFiles((dir, name) -> !name.equals(".DS_Store"));
I'm trying to write this script that takes an Excel sheet, gets all the names of files from the cells, and moves each of those files to a specific folder. I've already got most of the code done, I just need to be able to search for each file in the source directory using just its title. Another problem is that I'm searching for multiple file types (.txt, .repos, .xlsx, .xls, .pdf, and some files don't have extensions), I only can search by the file name without the extension.
In my findAndMoveFiles method, I've got an ArrayList of each File and a Guava Multimap of XSSFCells to Strings (a cell is one cell from the Excel file and a String is the name of the folder it needs to go into, one to many relationship) as parameters. What I've got right now for the method is this.
public static void findAndMoveFiles(List<File> files, Multimap<XSSFCell, String> innerCells) {
// For each file, get its values (folders), and put that file in each of those folders
for (XSSFCell cell : innerCells.keySet()) {
// find the file in the master directory
//Finder f = new Finder();
//if (f.canBeFound(FOLDER, cell.getStringCellValue())) {
File file = find(FOLDER, cell.getStringCellValue());
//System.out.println(file.getAbsolutePath());
//List<String> values = new ArrayList(innerCells.get(cell));
/*for (String folder : values) {
File copy = file;
if (copy != null) {
System.out.println(folder);
System.out.println(copy.getAbsolutePath());
if (copy.renameTo(new File("C:\\strobell\\" + folder + "\\" + copy.getAbsolutePath()))) {
System.out.println(copy.getName() + " has been moved successfully.");
} else {
System.out.println(copy.getName() + " has failed to move.");
}
}
}*/
//}
}
}
public static File find(File dir, String fileName) {
String files = "";
File[] listOfFiles = dir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getAbsolutePath();
if (files.equals(fileName)) {
return listOfFiles[i];
}
}
}
return null;
}
I commented out parts because it wasn't working. I was getting NullPointerExceptions because some files were being returned as null. I know that it's returning null, but each file should be found.
If there are any 3rd party libraries that can do this, that would be amazing, I've been racking my brain on how to do this properly.
Instead of
File[] listOfFiles = dir.listFiles();
use
File[] listOfFiles = dir.list(new FileNameFilter() {
public boolean accept(File dir, String name) {
if( /* code to check if file name is ok */ ) {
return true;
}
return false;
}
}););
Then you can code your logic on the file names in the condition.
Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer.
Heres my code:
File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
if (f.isFile())
String name = f.getName();
}
This doesnt seem to work dont know why.
I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array.
public File[] GetFiles(String DirectoryPath) {
File f = new File(DirectoryPath);
f.mkdirs();
File[] file = f.listFiles();
return file;
}
public ArrayList<String> getFileNames(File[] file){
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
change
File[] file= new File(sdCardRoot+"path");
with
File[] file= new File(sdCardRoot, "path");
and make sure the directory path exits
Just Check this:
List<File> files = getListFiles(new File("YOUR ROOT"));
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
Since sdCardRoot is instance of File, sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path".
However, calling file.toString() returns file name, but not absolute path. You need to call sdCardRoot.getAbsolutePath() + "path".
Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage.
File f=new File("C:/");
File fList[] = f.listFiles();
When i use this it list all system file as well as hidden files.
and this cause null pointer exception when i use it to show in jTree like this:
public void getList(DefaultMutableTreeNode node, File f) {
if(f.isDirectory()) {
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
File fList[] = f.listFiles();
for(int i = 0; i < fList.length; i++)
getList(child, fList[i]);
}
}
What should i do so that it do not give NullPointerException and show only non hidden and non system files in jTree?
Do this for hidden files:
File root = new File(yourDirectory);
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return !file.isHidden();
}
});
This will not return hidden files.
As for system files, I believe that is a Windows concept and therefore might not be supported by File interface that tries to be system independent. You can use Command line commands though, if those exist.
Or use what #Reimeus had in his answer.
Possibly like
File root = new File("C:\\");
File[] files = root.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
Path path = Paths.get(file.getAbsolutePath());
DosFileAttributes dfa;
try {
dfa = Files.readAttributes(path, DosFileAttributes.class);
} catch (IOException e) {
// bad practice
return false;
}
return (!dfa.isHidden() && !dfa.isSystem());
}
});
DosFileAttributes was introduced in Java 7.
If running under Windows, Java 7 introduced DosFileAttributes which enables system and hidden files to be filtered. This can be used in conjunction with a FileFilter
Path srcFile = Paths.get("myDirectory");
DosFileAttributes dfa = Files.readAttributes(srcFile, DosFileAttributes.class);
System.out.println("System File? " + dfa.isSystem());
System.out.println("Hidden File? " + dfa.isHidden());
If you are trying to list all files in C:/ please keep in mind that there are other files also which are neither hidden nor system files, but that still won't open because they require special privileges/permissions. So:
String[] files = file.list();
if (files!=null) {
for (String f : files) open(f);
}
So just compare if the array is null or not and design your recursion in such a way that it just skips those files whose array for the list() function is null.
private void nodes(DefaultMutableTreeNode top, File f) throws IOException {
if (f.isDirectory()) {
File[] listFiles = f.listFiles();
if (listFiles != null) {
DefaultMutableTreeNode b1[] = new DefaultMutableTreeNode[listFiles.length];
for (int i = 0; i < b1.length; i++) {
b1[i] = new DefaultMutableTreeNode(listFiles[i].toString());
top.add(b1[i]);
File g = new File(b1[i].toString());
nodes(b1[i], g);
}
}
}
Here is the code I used to create a window file explorer using jtree.
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);
}