Return values in recursive function in java - java

here is a simple function that searches for a file in a given folder and its subfolders i am able to find the file but somehow the return value is a null and can someone also explain what happens in the stack when we use recursive functions if you can relate it to my scenario it would be great...
File getFileInFolder(File folder, String fileName) {
//System.out.println(" PathTo : "+folder.getAbsolutePath());
File [] files = folder.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
return getFileInFolder(files[i],fileName);
} else {
//System.out.println(" file : "+files[i].getName());
if (files[i].getName().equals(fileName)) {
System.out.println(" Found file : "+files[i].getName());
return files[i];
}
}
}
}
return null;
}

Let's say that you're looking for a.txt in the following folder:
root
sub1
b.txt
sub2
a.txt
What your algorithm does is
List the files in root. That returns sub1 and sub2.
Iterate through the files. If the file is a directory, return the result of the method on this directory
So, the algorithm will search only in sub1, and that will return null.
You need to continue searching in other directories if the file wasn't found in the first one:
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
File resultForSubDirectory = getFileInFolder(files[i], fileName);
if (resultForSubDirectory != null) {
return resultForSubDirectory;
} // else: continue looping
}
else {
...
}
}

i have solved it using a bool variable filefound and i break all the loops in the stack, don"t know if it is the best way to do it but it works for me
boolean filefound = false;
File getFileInFolder(File folder, String fileName) {
filefound = false;
//System.out.println(" PathTo : "+folder.getAbsolutePath());
File [] files = folder.listFiles();
File file = null;
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
file = getFileInFolder(files[i],fileName);
if(filefound) {
file= files[i];
break;
}
} else {
//System.out.println(" file : "+files[i].getName());
if (files[i].getName().equals(fileName)) {
System.out.println(" Found file : "+files[i].getName());
file= files[i];
filefound = true;
break;
}
}
}
}
return file;
}

Related

Get list files documents in android Java, NO SUCH FILE OR DIRECTORY

please help me this code, I don't know how android manage files & folders
I use a function that get the list of files documents in android storage, but after check each file, that result illegal, exception throw: No such file or directory
**public void doJob() {
Log.d(TAG, "Check01952039847501: " + mListFileInput.size());
// list 27 files input
for (int i = 0; i < mListFileInput.size(); i++) {
File file = new File(mListFileInput.get(i));
Log.d(TAG, "Check010684946823046 = " + file);
// /storage/0F37-7BF9/aliasBook2/Da-Vinci.epub
Log.d(TAG, "Check010684946823046: check file: " + file.exists());
// false
try {
ZipFile zipFile = new ZipFile(file);
} catch (IOException e) {
e.printStackTrace();
// Exception throw "such file or directory android", all files
}
}
}**
Note: To get that mListFileInput list, I use recuisive function this:
**public void recuisiveGetEbook(File directory) {
File[] fileList = directory.listFiles();
if (fileList != null) {
for (int i = 0; i < fileList.length; i++) {
File file = fileList[i];
if (!file.getPath().contains("/Android")
&& !file.getPath().contains("/data")
&& !file.isHidden()) {
// if that is file
if (file.isFile() && file.exists() && file.canRead()) {
if (file.getName().endsWith(".epub")) {
lstResult.add(fileList[i].getPath());
Log.d(TAG, "Check019252357: " + fileList[i].getPath());
}
} // if that is folder
else recuisive1(fileList[i]);
}
}
}
}**

List files and files of subdirectories from a given folder

I try to list all the files from a folder and its subdirectories to be uploaded one by one. It couldn't list files from subfolders of folder, just uses files from same folder multiple times.
int num=1;
public void listFilesAndFilesSubDirectories(String directoryName) throws InterruptedException {
File directory = new File(directoryName);
File[] fList = directory.listFiles();
Arrays.sort(fList);
String filestatus;
for (File file : fList){
if (file.isFile() && !(file.getName().contains("nfo"))){
int index = file.getName().lastIndexOf("_");
if(index <= 0){
filestatus="INVALID";
}else{
filestatus = file.getName().substring(0, index);
}
} else if (file.isDirectory()){
listFilesAndFilesSubDirectories(file.getParent());
}
num++;
}
}
Replace:
listFilesAndFilesSubDirectories(file.getParent());
with:
listFilesAndFilesSubDirectories(file.getAbsolutePath());
You can also use the "Tree" :
private DefaultMutableTreeNode listFile(File file, DefaultMutableTreeNode node){
int count = 0;
if(file.isFile())
return new DefaultMutableTreeNode(file.getName());
else{
File[] list = file.listFiles();
if(list == null)
return new DefaultMutableTreeNode(file.getName());
for(File nom : list){
count++;
//not more than 5 childs node
if(count < 5){
DefaultMutableTreeNode subNode;
if(nom.isDirectory()){
subNode = new DefaultMutableTreeNode(nom.getName()+"\\");
node.add(this.listFile(nom, subNode));
}else{
subNode = new DefaultMutableTreeNode(nom.getName());
}
node.add(subNode);
}
}
return node;
}
}
see more here
The doc is in french but you may find what you need.

android string array nullpointerexception on older android versions

This code works fine on android 4.4, 5.0, 5.1 , 6.0
File file = new File("/storage/emulated/0//Videos/");
String[] myFiles;
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
myFile.delete();
}
But when i use this for android 4.0, 4.1, 4.2 i get java.lang.NullPointerException referring at line
for (int i = 0; i < myFiles.length; i++)
So i try to initialize the String,
String[] myFiles = new String[100] //just big value
But android studio shows initializer "new String[100]" is redundent and error is not resolved.
Why does this happen?
Thanks..!
The javadoc for File.list() says that it can return null. You should always check for this whenever you call it and handle it correctly unless you are absolutely certain it will not return null.
This is because you are not checking your folder is null or not make sure your directory contains file
File file = new File("/storage/emulated/0//Videos/");
String[] myFiles;
if (file == null) {
} else {
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
if(myFile.exists())
myFile.delete();
}
}
And if you want to delete whole directory than you can use this sample method
public void deleteDirectory(File file) {
if( file.exists() ) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
file.delete();
}
}

how recursively to add some .txt files from a folder and sub folder's in Java

I have been trying to use some data from some txt files (I want to find some words in these txt files) from a folder and sub folder's recursively (I have to find these txt files from some folders that all of them are in the same folder) in Java, how can I do it?
void processInput(final String directoryName) {
final File inputDirectory = new File(directoryName);
for (final String inputFile : inputDirectory.list()) {
final File file = new File(directoryName + File.separator
+ inputFile);
if (file.isDirectory()) {
processInput(directoryName + File.separator + inputFile);
} else {
processFile(file);
}
}
}
I think this is good way for do it:
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}

Deleting Multiple Files Java (Android)

I'm new to programming Android, and I want to delete Files on the sd-card. This is my current (working) code...
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "ApplifierVideoCache");
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
Now I want to delete multiple files, but dont want to mention each file with that big block. Am I able to combine all files in one variable? Thanks ;)
Make a recursive method:
/*
* NOTE: coded so as to work around File's misbehaviour with regards to .delete(),
* which does not throw an exception if it fails -- or why you should use Java 7's Files
*/
public void doDelete(final File base)
throws IOException
{
if (base.isDirectory()) {
for (final File entry: base.listFiles())
doDelete(entry);
return;
}
if (!file.delete())
throw new IOException ("Failed to delete " + file + '!');
}
Another possibility would be using the Apache commons-io library and calling
if (file.isDirectory())
FileUtils.deleteDirectory(File directory);
else {
if(!file.delete())
throw new IOException("Failed to delete " + file);
}
You should make a method out of this chunk of code, pass file name and call it whenever you like:
public void DeleteFile(String fileName) {
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), fileName);
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
}
File dir = new File(android.os.Environment.getExternalStorageDirectory(),"ApplifierVideoCache");
Then call
deletedir(dir);
public void deletedir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
listFile[i].delete();
}
}
}
or if your folder as sub folders then
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++)
{
if (listFile[i].isDirectory())
{
walkdir(listFile[i]);
} else
{
listFile[i].delete();
}
}
}
For kotlin
Create a array of path list
val paths: MutableList<String> = ArrayList()
paths.add("Yor path")
paths.add("Yor path")
.
.
delete file for each path
try{
paths.forEach{
val file = File(it)
if(file.exists(){
file.delete()
}
}
}catch(e:IOException){
}

Categories