How to detect if a file(with any extension) exist in java - java

I am searching for a sound file in a folder and want to know if the sound file exist may it be .mp3,.mp4,etc.I just want to make sure that the filename(without extension) exists.
eg.File searching /home/user/desktop/sound/a
return found if any of a.mp3 or a.mp4 or a.txt etc. exist.
I tried this:
File f=new File(fileLocationWithExtension);
if(f.exist())
return true;
else return false;
But here I have to pass the extension also otherwise its returning false always
To anyone who come here,this is the best way I figured out
public static void main(String[] args) {
File directory=new File(your directory location);//here /home/user/desktop/sound/
final String name=yourFileName; //here a;
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
if(fileName.lastIndexOf(".")==-1) return false;
if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
return true;
else return false;
}
});
if(myFiles.length()>0)
System.Out.println("the file Exist");
}
Disadvantage:It will continue on searching even if the file is found which I never intended in my question.Any suggestion is welcome

This code will do the trick..
public static void listFiles() {
File f = new File("C:/"); // use here your file directory path
String[] allFiles = f.list(new MyFilter ());
for (String filez:allFiles ) {
System.out.println(filez);
}
}
}
class MyFilter implements FilenameFilter {
#Override
//return true if find a file named "a",change this name according to your file name
public boolean accept(final File dir, final String name) {
return ((name.startsWith("a") && name.endsWith(".jpg"))|(name.startsWith("a") && name.endsWith(".txt"))|(name.startsWith("a") && name.endsWith(".mp3")|(name.startsWith("a") && name.endsWith(".mp4"))));
}
}
Above code will find list of files which has name a.
I used 4 extensions here to test(.jpg,.mp3,.mp4,.txt).If you need more just add them in boolean accept() method.
EDIT :
Here is the most simplified version of what OP wants.
public static void filelist()
{
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles)
{
if (file.isFile())
{
String[] filename = file.getName().split("\\.(?=[^\\.]+$)"); //split filename from it's extension
if(filename[0].equalsIgnoreCase("a")) //matching defined filename
System.out.println("File exist: "+filename[0]+"."+filename[1]); // match occures.Apply any condition what you need
}
}
}
Output:
File exist: a.jpg //These files are in my C drive
File exist: a.png
File exist: a.rtf
File exist: a.txt
File exist: a.mp3
File exist: a.mp4
This code checks all the files of a path.It will split all filenames from their extensions.And last of all when a match occurs with defined filename then it will print that filename.

If you're looking for any file with name "a" regardless of the suffix, the glob that you're looking for is a{,.*}. The glob is the type of regular expression language used by shells and the Java API to match filenames. Since Java 7, Java has support for globs.
This Glob explained
{} introduces an alternative. The alternatives are separated with ,. Examples:
{foo,bar} matches the filenames foo and bar.
foo{1,2,3} matches the filenames foo1, foo2 and foo3.
foo{,bar} matches the filenames foo and foobar - an alternative can be empty.
foo{,.txt} matches the filenames foo and foo.txt.
* stands for any number of characters of any kind, including zero characters. Examples:
f* matches the filenames f, fa, faa, fb, fbb, fab, foo.txt - every file that's name starts with f.
The combination is possible. a{,.*} is the alternatives a and a.*, so it matches the filename a as well as every filename that starts with a., like a.txt.
A Java program that lists all files in the current directory which have "a" as their name regardless of the suffix looks like this:
import java.io.*;
import java.nio.file.*;
public class FileMatch {
public static void main(final String... args) throws IOException {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
for (final Path entry : stream) {
System.out.println(entry);
}
}
}
}
or with Java 8:
import java.io.*;
import java.nio.file.*;
public class FileMatch {
public static void main(final String... args) throws IOException {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
stream.forEach(System.out::println);
}
}
}
If you have the filename in a variable and you want to see whether it matches the given glob, you can use the FileSystem.getPathMatcher() method to obtain a PathMatcher that matches the glob, like this:
final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:a{,.*}");
final boolean matches = pathMatcher.matches(new File("a.txt").toPath());

You can try some thing like this
File folder = new File("D:\\DestFile");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println("found ."+file.getName().substring(file.getName().lastIndexOf('.')+1));
}
}

Try this:
File parentDirToSearchIn = new File("D:\\DestFile");
String fileNameToSearch = "a";
if (parentDirToSearchIn != null && parentDirToSearchIn.isDirectory()) {
String[] childFileNames = parentDirToSearchIn.list();
for (int i = 0; i < childFileNames.length; i++) {
String childFileName = childFileNames[i];
//Get actual file name i.e without any extensions..
final int lastIndexOfDot = childFileName.lastIndexOf(".");
if(lastIndexOfDot>0){
childFileName = childFileName.substring(0,lastIndexOfDot );
if(fileNameToSearch.equalsIgnoreCase(childFileName)){
System.out.println(childFileName);
}
}//otherwise it could be a directory or file without any extension!
}
}

You could make use of the SE 7 DirectoryStream class :
public List<File> scan(File file) throws IOException {
Path path = file.toPath();
try (DirectoryStream<Path> paths = Files.newDirectoryStream(path.getParent(), new FileNameFilter(path))) {
return collectFilesWithName(paths);
}
}
private List<File> collectFilesWithName(DirectoryStream<Path>paths) {
List<File> results = new ArrayList<>();
for (Path candidate : paths) {
results.add(candidate.toFile());
}
return results;
}
private class FileNameFilter implements DirectoryStream.Filter<Path> {
final String fileName;
public FileNameFilter(Path path) {
fileName = path.getFileName().toString();
}
#Override
public boolean accept(Path entry) throws IOException {
return Files.isRegularFile(entry) && fileName.equals(fileNameWithoutExtension(entry));
}
private String fileNameWithoutExtension(Path candidate) {
String name = candidate.getFileName().toString();
int extensionIndex = name.lastIndexOf('.');
return extensionIndex < 0 ? name : name.substring(0, extensionIndex);
}
}
This will return files with any extension, or even without extension, as long as the base file name matches the given File, and is in the same directory.
The FileNameFilter class makes the stream return only the matches you're interested in.

public static boolean everExisted() {
File directory=new File(your directory location);//here /home/user/desktop/sound/
final String name=yourFileName; //here a;
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
if(fileName.lastIndexOf(".")==-1) return false;
if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
return true;
else return false;
}
});
if(myFiles.length()>0)
return true;
}
}
When it returns, it will stop the method.

Try this one
FileLocationWithExtension = "nameofFile"+ ".*"

Related

Find directory and get its absolute path [duplicate]

What is the best way to find a directory with a specific name in Java? The directory that I am looking for can be located either in the current directory or one of its subdirectories.
In Java 8 via the streams API:
Optional<Path> hit = Files.walk(myPath)
.filter(file -> file.getFileName().equals(myName))
.findAny();
The #walk is lazy, so any short-circuiting terminal operation will optimize the IO required.
To walk the file tree, FileVisitor interface can be used.
Please see the tutorial. Please see Find sample codes also.
Your solution will include the use of File.listFiles(String)
java.io.File API reference
As you mentioned recursion should cater to this requirement
import java.io.File;
public class CheckFile {
private static boolean foundFolder = false;
public static void main(String[] args) {
File dir = new File("currentdirectory");
findDirectory(dir);
}
private static void findDirectory(File parentDirectory) {
if(foundFolder) {
return;
}
File[] files = parentDirectory.listFiles();
for (File file : files) {
if (file.isFile()) {
continue;
}
if (file.getName().equals("folderNameToFind")) {
foundFolder = true;
break;
}
if(file.isDirectory()) {
findDirectory(file);
}
}
}
}
Something like:
public static final File findIt(File rootDir, String fileName) {
File[] files = rootDir.listFiles();
List<File> directories = new ArrayList<File>(files.length);
for (File file : files) {
if (file.getName().equals(fileName)) {
return file;
} else if (file.isDirectory()) {
directories.add(file);
}
}
for (File directory : directories) {
File file = findIt(directory);
if (file != null) {
return file;
}
}
return null;
}
Divide and conquer? A naive approach: For every directory, you may start a task, it does the following:
list every directory
if the list contains a matching directory, prints and exit the application
start a task for every directory.
Or, you should use the concept of Recursively search the file until it found: Here is the Code:
String name; //to hold the search file name
public String listFolder(File dir) {
int flag;
File[] subDirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
System.out.println("File of Directory: " + dir.getAbsolutePath());
flag = Listfile(dir);
if (flag == 0) {
System.out.println("File Found in THe Directory: " + dir.getAbsolutePath());
Speak("File Found in THe Directory: !!" + dir.getAbsolutePath());
return dir.getAbsolutePath();
}
for (File folder : subDirs) {
listFolder(folder);
}
return null;
}
private int Listfile(File dir) {
boolean ch = false;
File[] files = dir.listFiles();
for (File file : files) {
Listfile(file);
if (file.getName().indexOf(name.toLowerCase()) != -1) {//check all in lower case
System.out.println(name + "Found Sucessfully!!");
ch = true;
}
}
if (ch) {
return 1;
} else {
return 0;
}
}

How to delete files with a certain extension from a folder in Andorid

I m a newbie in Android. I generate a record audio file, generate a text file, zip the two files and encrypt them.
I want to delete the following extensions .txt, .mp4 and .zip. I only want my encrypted file to remain in my directory containing .txt and .mp4
I did research and come across the following source and try to modified it.
private static final String DEFAULT_STORAGE_DIRECTORY = "Recorder";
private static final String FILE_RECORD_EXT = ".mp4";
private static final String FILE_INI_EXT = ".txt";
private static final String FILE_ZIP_EXT = ".zip";
public static void main(String args[]) {
new FileChecker().deleteFile(DEFAULT_STORAGE_DIRECTORY,FILE_RECORD_EXT,FILE_TXT_EXT);
}
public void deleteFile(String folder, String ext, String fileTxtExt){
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
String[] list = dir.list(filter);
if (list.length == 0) return;
//Files
File fileDelete;
for (String file : list){
String temp = new StringBuffer(DEFAULT_STORAGE_DIRECTORY)
.append(File.separator)
.append(file).toString();
fileDelete = new File(temp);
boolean isdeleted = fileDelete.delete();
System.out.println("file : " + temp + " is deleted : " + isdeleted);
}
}
//inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
Your help will be appreciated.
void deleteFiles(String folder, String ext)
{
File dir = new File(folder);
if (!dir.exists())
return;
File[] files = dir.listFiles(new GenericExtFilter(ext));
for (File file : files)
{
if (!file.isDirectory())
{
boolean result = file.delete();
Log.d("TAG", "Deleted:" + result);
}
}
}
Here is my working code for this. Please follow the comments inline to understand it's flow & function.
//dirpath= Directory path which needs to be checked
//ext= Extension of files to deleted like .csv, .txt
public void deleteFiles(String dirPath, String ext) {
File dir = new File(dirPath);
//Checking the directory exists
if (!dir.exists())
return;
//Getting the list of all the files in the specific direcotry
File fList[] = dir.listFiles();
for (File f : fList) {
//checking the extension of the file with endsWith method.
if (f.getName().endsWith(ext)) {
f.delete();
}
}
}

Get all folders with a given name

I am searching for a solution to find all folders with the same name in a given directory.
So my folder structure looks like this:
Root
| | |
android windows ios
| | | | | |
focus normal focus normal focus normal
Note: There are more folders between the clients and the iconsets, that's why I need recursion.
I want to get a ArrayList with all the pathes of e.g. Normal folders.
Although recursion confuses me a lot all the time I couldnt to it.
This was my first try, which should return ALL contained directories in the Root folder (parameter path). The String iconset should define the name of the searched folder afterwards.
private static ArrayList<String> getAllIconSetFolders(String path, String iconset) {
ArrayList<String> pathes = new ArrayList<String>();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file != null && file.isDirectory()) {
pathes.addAll(getAllIconSetFolders(file.getAbsolutePath(), iconset));
}
}
return pathes;
}
It will return an empty ArrayList in this case.
How can I get all paths for (The normal folders when String iconset = "normal") so my result would look like:
"Root/android/[...]/normal"
"Root/windows/[...]/normal"
"Root/ios/[...]/normal"
I've just tested the following code and it appears to work correctly:
public static List<File> findDirectoriesWithSameName(String name, File root) {
List<File> result = new ArrayList<>();
for (File file : root.listFiles()) {
if (file.isDirectory()) {
if (file.getName().equals(name)) {
result.add(file);
}
result.addAll(findDirectoriesWithSameName(name, file));
}
}
return result;
}
Your original code was almost there, you just omitted the part where you actually add matching directories to your result list.
Tested with:
C:\tmp\foo
C:\tmp\foo\bar
C:\tmp\foo\baz
C:\tmp\foo\baz\foo
C:\tmp\foo\baz\foo\bar
Using
public static void main(String[] args) throws Exception {
List<File> files = findDirectoriesWithSameName("foo", new File("C:\\tmp"));
for (File f :files) {
System.out.println(f);
}
}
Output:
C:\tmp\foo
C:\tmp\foo\baz\foo
You need to add the directory name to pathes otherwise it will always be empty. Your code should be something like:
private static List<String> getAllIconSetFolders(String path, String iconset)
{
List<String> pathes = new ArrayList<String>();
File folder = new File(path);
for (File file : folder.listFiles())
{
if (file.isDirectory())
{
if (file.getName().equals(iconset))
{
pathes.add(file.getAbsolutePath());
}
else
{
pathes.addAll(getAllIconSetFolders(file.getAbsolutePath(), iconset));
}
}
}
return pathes;
}
This assumes the iconset is the name of the directory you are looking for and that that directories with that name can exist multiple times in the directory tree.
While searching for directory inside a directory, one elegant way is to use FileFilter or for name matching use FileNameFilter. On top of it you apply standard recursive ways the complete solution would be:
static void test()
{
File f = new File("e:\\folder");
List<File> res = new ArrayList<File>();
search(f, res, "normal");
System.out.println(res);
search(f, res, "focus");
System.out.println(res);
}
static void search(File f, List<File> res, final String search)
{
if(f.isDirectory())
{
File[] result = f.listFiles(new FilenameFilter()
{
public boolean accept(File file, String name)
{
return file.isDirectory() && name.equals(search);
}
});
if(result != null)
{
for(File file : result)
{
res.add(file);
}
}
//search further recursively
File[] allFiles = f.listFiles();
if(allFiles != null)
{
for(File file: allFiles)
{
search(file, res, search);
}
}
}
}
Or you can extend FileNameFilter as say NormalDirFilter or FocusDirFilter where you can hardcode specific folder search name. Use instances of these specific filters while listing file during recursion.
Tested. Works. Need Java 7.
public static void main(String[] args) {
List<String> paths = new ArrayList<String>();
getAllFolders("/path/to/folder", "normal", paths);
}
private static void getAllFolders(String path, String folderName, List<String> paths) throws Exception {
Path mainPath = Paths.get(path);
Iterator<Path> stream = Files.newDirectoryStream(mainPath).iterator();
while(stream.hasNext()) {
Path currentPath = stream.next();
String currentFolderName = currentPath.getFileName().toString();
if(currentFolderName.equals(folderName)) {
paths.add(currentPath.toString());
}
getAllFolders(currentPath.toString(), folderName, paths);
}
}
If you have this structure, could you not do
public static List<File> subdirectories(File root, String toFind) {
List<File> ret = new ArrayList<File>();
for(File dir : root.listFiles()) {
File dir2 = new File(dir, toFind);
if (dir2.isDirectory())
ret.add(dir2);
}
return ret;
}

Java - Search for files in a directory

This is supposed to be simple, but I can't get it - "Write a program that searches for a particular file name in a given directory." I've found a few examples of a hardcoded filename and directory, but I need both the dir and file name to be as entered by the user.
public static void main(String[] args) {
String fileName = args[0]; // For the filename declaration
String directory;
boolean found;
File dir = new File(directory);
File[] matchingFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String fileName) {
return true;
}
});
}
you can try something like this:
import java.io.*;
import java.util.*;
class FindFile
{
public void findFile(String name,File file)
{
File[] list = file.listFiles();
if(list!=null)
for (File fil : list)
{
if (fil.isDirectory())
{
findFile(name,fil);
}
else if (name.equalsIgnoreCase(fil.getName()))
{
System.out.println(fil.getParentFile());
}
}
}
public static void main(String[] args)
{
FindFile ff = new FindFile();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file to be searched.. " );
String name = scan.next();
System.out.println("Enter the directory where to search ");
String directory = scan.next();
ff.findFile(name,new File(directory));
}
}
Here is the output:
J:\Java\misc\load>java FindFile
Enter the file to be searched..
FindFile.java
Enter the directory where to search
j:\java\
FindFile.java Found in->j:\java\misc\load
Using Java 8+ features we can write the code in few lines:
protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(f -> f.getFileName().toString().equals(fileName))
.collect(Collectors.toList());
}
}
Files.walk returns a Stream<Path> which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.
Note that the documentation of Files.walk requires
This method must be used within a try-with-resources statement or
similar control structure to ensure that the stream's open directories
are closed promptly after the stream's operations have completed.
I'm using the try-resource-statement.
For advanced searches an alternative is to use a PathMatcher:
protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(matcher::matches)
.collect(Collectors.toList());
}
}
An example how to use it to find a certain file:
public static void main(String[] args) throws IOException {
String searchDirectory = args[0];
String fileName = args[1];
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
Collection<Path> find = find(searchDirectory, matcher);
System.out.println(find);
}
More about it: Oracle Finding Files tutorial
With **Java 8* there is an alternative that use streams and lambdas:
public static void recursiveFind(Path path, Consumer<Path> c) {
try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
StreamSupport.stream(newDirectoryStream.spliterator(), false)
.peek(p -> {
c.accept(p);
if (p.toFile()
.isDirectory()) {
recursiveFind(p, c);
}
})
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
}
So this will print all the files recursively:
recursiveFind(Paths.get("."), System.out::println);
And this will search for a file:
recursiveFind(Paths.get("."), p -> {
if (p.toFile().getName().toString().equals("src")) {
System.out.println(p);
}
});
This looks like a homework question, so I'll just give you a few pointers:
Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.
You're not using Scanner for anything, and it's not needed here, get rid of it.
Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.
If you want to use a dynamic filename filter you can implement FilenameFilter and pass in the constructor the dynamic name.
Of course this implies taht you must instantiate every time the class (overhead), but it works
Example:
public class DynamicFileNameFilter implements FilenameFilter {
private String comparingname;
public DynamicFileNameFilter(String comparingName){
this.comparingname = comparingName;
}
#Override
public boolean accept(File dir, String name) {
File file = new File(name);
if (name.equals(comparingname) && !file.isDirectory())
return false;
else
return true;
}
}
then you use where you need:
FilenameFilter fileNameFilter = new DynamicFileNameFilter("thedynamicNameorpatternYouAreSearchinfor");
File[] matchingFiles = dir.listFiles(fileNameFilter);
I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* #author Deepankar Sinha
*/
public class GetList {
public List<String> stack;
static List<String> lnkFile;
static List<String> progName;
int index=-1;
public static void main(String args[]) throws IOException
{
//var-- progFile:Location of the file to be search.
String progFile="C:\\";
GetList obj=new GetList();
String temp=progFile;
int i;
while(!"&%##".equals(temp))
{
File dir=new File(temp);
String[] directory=dir.list();
if(directory!=null){
for(String name: directory)
{
if(new File(temp+name).isDirectory())
obj.push(temp+name+"\\");
else
if(new File(temp+name).isFile())
{
try{
//".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
{
//obj.addFile(temp+name,name);
System.out.println(temp+name);
}
}catch(StringIndexOutOfBoundsException e)
{
//debug purpose
System.out.println("ERROR******"+temp+name);
}
}
}}
temp=obj.pop();
}
obj.display();
// for(int i=0;i<directory.length;i++)
// System.out.println(directory[i]);
}
public GetList() {
this.stack = new ArrayList<>();
this.lnkFile=new ArrayList<>();
this.progName=new ArrayList<>();
}
public void push(String dir)
{
index++;
//System.out.println("PUSH : "+dir+" "+index);
this.stack.add(index,dir);
}
public String pop()
{
String dir="";
if(index==-1)
return "&%##";
else
{
dir=this.stack.get(index);
//System.out.println("POP : "+dir+" "+index);
index--;
}
return dir;
}
public void addFile(String name,String name2)
{
lnkFile.add(name);
progName.add(name2);
}
public void display()
{
GetList.lnkFile.stream().forEach((lnkFile1) -> {
System.out.println(lnkFile1);
});
}
}
The Following code helps to search for a file in directory and open its location
import java.io.*;
import java.util.*;
import java.awt.Desktop;
public class Filesearch2 {
public static void main(String[] args)throws IOException {
Filesearch2 fs = new Filesearch2();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file to be searched.. " );
String name = scan.next();
System.out.println("Enter the directory where to search ");
String directory = scan.next();
fs.findFile(name,new File(directory));
}
public void findFile(String name,File file1)throws IOException
{
File[] list = file1.listFiles();
if(list!=null)
{
for(File file2 : list)
{
if (file2.isDirectory())
{
findFile(name,file2);
}
else if (name.equalsIgnoreCase(file2.getName()))
{
System.out.println("Found");
System.out.println("File found at : "+file2.getParentFile());
System.out.println("Path diectory: "+file2.getAbsolutePath());
String p1 = ""+file2.getParentFile();
File f2 = new File(p1);
Desktop.getDesktop().open(f2);
}
}
}
}
}
This method will recursively search thru each directory starting at the root, until the fileName is found, or all remaining results come back null.
public static String searchDirForFile(String dir, String fileName) {
File[] files = new File(dir).listFiles();
for(File f:files) {
if(f.isDirectory()) {
String loc = searchDirForFile(f.getPath(), fileName);
if(loc != null)
return loc;
}
if(f.getName().equals(fileName))
return f.getPath();
}
return null;
}
public class searchingFile
{
static String path;//defining(not initializing) these variables outside main
static String filename;//so that recursive function can access them
static int counter=0;//adding static so that can be accessed by static methods
public static void main(String[] args) //main methods begins
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the path : ");
path=sc.nextLine(); //storing path in path variable
System.out.println("Enter file name : ");
filename=sc.nextLine(); //storing filename in filename variable
searchfile(path);//calling our recursive function and passing path as argument
System.out.println("Number of locations file found at : "+counter);//Printing occurences
}
public static String searchfile(String path)//declaring recursive function having return
//type and argument both strings
{
File file=new File(path);//denoting the path
File[] filelist=file.listFiles();//storing all the files and directories in array
for (int i = 0; i < filelist.length; i++) //for loop for accessing all resources
{
if(filelist[i].getName().equals(filename))//if loop is true if resource name=filename
{
System.out.println("File is present at : "+filelist[i].getAbsolutePath());
//if loop is true,this will print it's location
counter++;//counter increments if file found
}
if(filelist[i].isDirectory())// if resource is a directory,we want to inside that folder
{
path=filelist[i].getAbsolutePath();//this is the path of the subfolder
searchfile(path);//this path is again passed into the searchfile function
//and this countinues untill we reach a file which has
//no sub directories
}
}
return path;// returning path variable as it is the return type and also
// because function needs path as argument.
}
}
I tried many ways to find the file type I wanted, and here are my results when done.
public static void main( String args[]){
final String dir2 = System.getProperty("user.name"); \\get user name
String path = "C:\\Users\\" + dir2;
digFile(new File(path)); \\ path is file start to dig
for (int i = 0; i < StringFile.size(); i++) {
System.out.println(StringFile.get(i));
}
}
private void digFile(File dir) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".mp4");
}
};
String[] children = dir.list(filter);
if (children == null) {
return;
} else {
for (int i = 0; i < children.length; i++) {
StringFile.add(dir+"\\"+children[i]);
}
}
File[] directories;
directories = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
public boolean accept(File dir, String name) {
return !name.endsWith(".mp4");
}
});
if(directories!=null)
{
for (File directory : directories) {
digFile(directory);
}
}
}

How do i read a folder and display the contents in java.

I'm creating a videogame (textbased) in java, and i need to read a folder to display several .java file names as the savegames. how do i do this?
Thanks.
Use File class, and its methods list() or listFiles():
String folderPath = ...;
for(String fileName : new File(folderPath).list())
{
if(fileName.endsWith(".java") && fileName.contains("savegames"))
{
System.out.println(fileName);
}
}
Also you can use the same methods with a FilenameFilter, which are list(FilenameFilter filter) or listFiles(FilenameFilter filter):
String folderPath = "";
FilenameFilter filter = new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.endsWith(".java") && name.contains("savegames");
}
};
for(String fileName : new File(folderPath).list(filter))
{
System.out.println(fileName);
}

Categories