Searching for specific files on a device - java

I'm a newcomer to mobile programming and want to start off with a little Musicplayer-App. I need to search for all files which end with .mp3, .m4a, .wav, and so on. To do this, I want to first get a list of all files and then filter out the audio-files.
However, when I use getExternalStorageDirectory to get the path to the storage it returns "/storage/3139-6333", which is obviously not correct.
Basically I'm just curious why I get this result and how to fix it.
It's to be assumed that READ_EXTERNAL_STORAGE is permitted.
Thanks in advance.
String state = Environment.getExternalStorageState();
if ((Environment.MEDIA_MOUNTED.equals(state)||Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)))
{
File sd_card = Environment.getExternalStorageDirectory(); //"/storage/3139-6333"
File[] listFile = sd_card .listFiles(); //null
}

I guess you already have the path where you wish to do file search, if yes then you can use basic dfs algorithm to search your desired file.
below is example code for that, you can put any format in end to check all files for it.
public void search(String path){
File file = new File(path);
File[] files = file.listFiles();
if (files!=null) {
for (File f : files) {
if (f.isDirectory()) {
this.search(f.getAbsolutePath());
}
if (f.getAbsolutePath().endsWith(".txt")) {
System.out.println(f.getAbsolutePath());
}
}
}
}
hope this will help.

Related

Access file without filename

I have a folder in a directory. I know, there is always only one file and it's a .txt file. But I don't know the filename.
How can I access it in Java? How must the path look like?
You could open the directory and go over its contents until you find the file:
public static File getTextFileInDirectory(String dirPath) {
File dir = new File(dirPath);
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().endsWith(".txt")) {
return f;
}
}
return null;
}
EDIT:
Based on the comments below, if it's safe to assume the directory always has a file in it, and there's nothing else in the directory (e.g., subdirectories), this code can be greatly simplified:
public static File getTextFileInDirectory(String dirPath) {
return new File(dirPath).listFiles()[0];
}
Since you know there will only be one file in the directory, you can get an array of the directory's files and return the first element if it exists, or null if it doesn't.
public static File getFileFromDir(File directory) {
File[] dirFiles = directory.listFiles();
return dirFiles.length > 0 ? dirFiles[0] : null;
}

Java I/O Opening Files in External Program

I have a Java program that I am using to scan a directory to look for certain files. It finds the files but now I am trying to get the code to open the files once it finds them, but I am not sure how to do that.
Here a part of my code
File file = new File("/Users/******/Desktop/******");
String[] A = file.list();
File[] C = file.listFiles();
for (String string : A) {
if (string.endsWith(".txt")) {
System.out.println(string);
}
if (string.contains("******")) {
System.out.println("It contains X file");
}
}
I am trying to get it so once it finds the files ending in .txt, it opens all of them
I have tried using Google on how to solve his, I came across .getRuntime() and so I tried
try{
Runtime.getRuntime().exec("******.txt");
} catch(IOException e){
}
But I am not fully understanding how how this works. I am trying to get to so that once it finds the files it opens them. I am not trying to have the IDE open the text on the screen. I want the actual Notepad/TextEdit program to open.
File[] files = new File("/Users/******/Desktop/******").listFiles();
for (File f : files) {
String fileName = f.getName();
if (fileName.endsWith(".txt")) {
System.out.println(fileName);
}
if (fileName.contains("******")) {
System.out.println("It contains X file");
}
}

Search whole c drive for file type

Ok so part of my program searches the C drive for all mp3 files, the only problem is that it won't go into and subfolders. Here is my code so far.
public static List<String> ListFiles() {
List<String> files = new ArrayList<String>();
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile() && file.toString().contains(".mp3")) {
String fileS = file.getName();
files.add(fileS);
}
}
return files;
}
Try a recursive approach. The path is the current directory that you're in. Recursively call this on each folder and you will get to each file.
public void walk(String path) {
File root = new File(path);
File[] list = root.listFiles();
if (list == null) return;
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
}
else {
//do what you want with files
}
}
}
Test whether file is a folder. If it is, pass it to ListFiles and append the return value to files.
For this to work, you need to change ListFiles to accept a File object as argument and start your search with this File instead of with "C:/"
Look into DirectoryStream<Path> class and the Files.isDirectory() method. Basically what you want to do is to check whether each Path is a file or directory.
If it is a directory, you call your method again. Else, you continue iterating.
Globbing is also possible with a directory stream. Saves you a lot of time instead of having to manually check file extensions.
If you wish to continue with your method or with directory stream, you will need to make a few modifications to your program to accomodate recursion.
If you want to do this yourself, you need to make it recursive. Which is what Oswald is getting at. A recursive method is a method that calls itself. So when you search a folder, for each element in it, if its an mp3, add it to the list, if its a folder, call your method again passing that folder in as the input.
I know it's Java question but why not just use Groovy and do it like:
static List<String> listMp3s() {
List<String> files = []
File rootFolder = new File('C:/')
rootFolder.eachFileRecurse(FileType.FILES) {
if (it.name.endsWith('.mp3')) {
files << it.name
}
}
return files
}

How to Delete files in /data/data/providers/downloads/cache on Android

I want to create and delete some files located in /data/data/providers/downloads/cache. So far, I can download target files and save in /data/data/providers/downloads/cache successfully, but when I trying to delete a file located in /data/data/providers/downloads/cache it fails in the end. My methods are as follows
File directory = new File("/data/data/providers/downloads/cache");
File[] files = directory.listFiles();
I want to list all files, so that I can find the target files need to be deleted.
I found that listFiles() method always return NULL, so my question is, can I use listFile() to the dir /data/data/providers/downloads/cache ?
Any ideals are welcomed.
BR
Alan
I use this method: when i want to delete all the files including the directory.
static public boolean deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for(int i = 0; i < files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
Log.d("Deleting Files", files[i].getPath());
}
}
return( path.delete() );
}
But android has it's own clear cache method you can use, but it requires you to actually save stuff to the cache. The problem might be that you never add anything to it, and you only have permission to clear your own cache?
How do I take advantage of Android's "Clear Cache" button Discusses the problem anyway :)
Good luck
EDIT:
Also, are you sure your file path is correct? You can use
Environment.getDownloadCacheDirectory()
in order to find the root directory to the cache i think?

How to make a String array containing file directories?

I am currently working on a project for school, it is Java based and I am using Eclipse on Linux Mint to write it. The assignment says use the statement String[] filenames = new java.io.File("icons).list(); to create an array of file names.
The problem is I am not sure what to do with this, I have spent the past few hours searching the Internet and my textbook, but to no avail. Does it need to be a separate method?
Below is my guess for the needed code in the model (the project is to make a matching game, with a GUI) the names will have to be converted later on into actual icons, but I am pretty sure I have that part figured out, I just can't seem to get the darn files into the array!!
Thanks in advance,
public String[] list() {
String[] fileNames = new java.io.File("icons").list();
return fileNames;
}
In Java, the File class does not necessary represent an "existing" file on the file system. For example:
File f = new File("some_unknown_unexisting_file.bob");
System.out.println(f.exists()); // most likely will print 'false'
Also, the class resolves the file from the current working directory. You may get this directory with
System.out.println(new File(".").getAbsolutePath());
In your case, if you can, I would suggest getting a File[] array with :
File[] files = new File("icons").listFiles(new FileFilter() {
#Override
public boolean accept(File f) {
return !f.isDirectory() && f.canRead();
}
});
for (File f : files) {
System.out.println(f.getAbsolutePath());
}
which will return an array of File objects which are not folders and that you can open for reading (note that this is not always true, but is just fine in your case).
But if you have to use list(), then this is equivalent :
File parent = new File("icons");
String[] fileStr = parent.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
File f = new File(dir, name);
return !f.isDirectory() && f.canRead();
}
});
for (String f : fileStr) {
System.out.println(new File(parent, f).getAbsolutePath());
}
Also, with your list of files (String[]), you can create an icon using :
String filename = fileStr[i]; // some file name within the array
ImageIcon icon = new ImageIcon("icons" + File.separator + filename);
or with your list of files (File[]), it is cleaner :
File file = files[i]; // some file within the File[] array
ImageIcon icon = new ImageIcon(file.getAbsolutePath());
Good luck.
The code you wrote looks okay. Are you sure the folder "icons" exists where Java is looking?
Try this:
File f = new File("icons");
System.out.println("Does icons exist?" + f.exists());
System.out.println("Is it a dir?" + f.isDirectory());
System.out.println("How many files does it contain?" + f.list().length);
Good luck!
I've had the same problem. When I tried moving the icons folder into the folder just before the src folder, it seems to work. Not sure what I will do when I submit the assignment, as for it to work in JCreator, I believe it has to be with the .java files.

Categories