Good morning everyone,
I'm stuck here with a code that I'm trying to make work. The goal of this code is to make a recursive algorithm to find all files that matched a target file name. Each string should store the pathname to the matching file. Return null if no matching files are found. Here is what I have so far:
import java.io.File;
import java.util.ArrayList;
public class ArrayListFiles
{
public static ArrayList searchForFile
(File dir, ArrayList filePaths, String target)
{
if (!dir.isDirectory())
return null;
else
{
File[] files=dir.listFiles();
for (int index = 0; index < filePaths; index++)
{
if(files[index].isFile())
{
if(files[index].getName().equals(target))
{
filePaths.add(files[index].toString());
}
}
else if(files[index].isDirectory())
searchForFile(files[index], filePaths, target);
}
}
return filePaths;
}
public static void main(String[] args)
{
ArrayList filePaths = new ArrayList();
File rootFolder = new File("F:\\java");
String targetFile = "sample.txt";
filePaths = searchForFile(rootFolder, filePaths, targetFile);
if(filePaths==null)
System.out.println("No file is found");
else
{
for (String string : filePaths)
{
System.out.println(string);
}
}
}
}
I am very new to programming and apologize in advance if I'm missing something very obvious. Thank you in advance and have a great day!
To resolve this error "Type mismatch: cannot convert from element type Object to String" for "for (String string : filePaths).
" change your code to this :
ArrayList<String> filePaths = new ArrayList<String>();
File rootFolder = new File("F:\\java");
String targetFile = "sample.txt";
filePaths = searchForFile(rootFolder, filePaths, targetFile);
if(filePaths==null)
System.out.println("No file is found");
else
{
for (String string : filePaths)
{
System.out.println(string);
}
}
FilePaths is an arraylist and it should be as follows :
for (int index = 0; index < files.length; index++)
Hope this helps .
This is probably your problem:
int index = 0; index < filePaths; index++
FilePaths is an arraylist and you're using it as integer. You probably wanted to iterate through files? Try
int index = 0; index < files.length; index++
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.