Get files list from apk expension file - android

How I can get files list of certain folder in expension apk file?
For assets I did it with:
String[] filesList = getAssets().list("some/path");
But for APK expension file I have only
getExpansionFile().getAllEntries();
which retreive all files.
But I need to move around folder, for example move to folder1, show files that place inside. And next move to subfolder1 (which place in folder1) and show fileslist there. I can't it hardcode, becouce files might be changed.
And again: how I can retreive files of certain folder in apk expension file?

Finally, I wrote my own implementation.
public class FileStructure {
public final String pathName;
// or TreeMap if order matter
public HashMap<String, FileStructure> files;
public FileStructure(String path){
this.pathName = path;
files = new HashMap<String, FileStructure>();
}
}
Getting apk expension file entries with java.util.zip.ZipFile:
ZipFile zf = new ZipFile(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/obb/" + getPackageName()
+ "/main.1." + getPackageName() + ".obb");
Enumeration zipEntries = zf.entries();
String fname;
while (zipEntries.hasMoreElements()) {
fname = ((ZipEntry) zipEntries.nextElement()).getName();
addToRoot(fname, root);
}
And parse it with in FileStructure class
private void addToRoot(String fname, FileStructure root) {
String[] directories = fname.split(File.separator);
FileStructure current = root;
for (int i = 0; i < directories.length; i++) {
if (!current.files.containsKey(directories[i])) {
current.files.put(directories[i], new FileStructure(directories[i]));
}
current = current.files.get(directories[i]);
}
}
But, I will appreciate, if someone share some better solution or find defect of my implementation!

Related

Activity to search all music files (or a particular extension) in Android storage

I am building an Android app that writes files in the format of my custom .fire extension.
I need to access them all at once and put them in a ListView. Could someone please help me to fetch them via an activity or Async Task Manager?
You can write an Async Task to fetch the .fire files from the folder into which you are writing them initially and dynamically add the filenames into the listview.
You can do something like this in your async task:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/"+FolderWhichContainsyourFiles);
File[] listOfFiles = dir.listFiles();
for (int count = 0; count < listOfFiles.length; count++) {
File file = listOfFiles[count];
if (file.isFile() && file.getName().endsWith(".fire")) {
String fileName = file.getName();
//Here you can dynamically add this name into the ListView
}
}
}
You need to use an ArrayAdapter and add elements to the ArrayAdapter dynamically. It is brilliantly explained here: Dynamically add elements to a listView Android
if you want to find files recursively:
private static List<File> filesList = new ArrayList<File>();
public static List<File> recursiveList(String filePath) {
try {
File[] dir = new File(filePath).listFiles();
for (File item : dir) {
if (item.isDirectory()) recursiveList(item.getAbsolutePath());
else if (item.isFile() && item.getName().endsWith(".fire"))
filesList.add(item);
}
return filesList;
} catch (Exception e) {
return null;
}
}
and to retrieve files in activity:
List<File> files = recursiveList("/sdcard/Music/");
for (File file : files)
adapterFilesList.add("" + file.getName());

How to read file names of the files that are present in the android's Internal/External storage

I am trying to program my own file manager for android. What I want to know is that how can I read the file names of all the files present in external/internal storage?
I want to read the file names and show them in a listview so the user could see what files are present in what folder. I know this thing is going to work in recursive manner as I have to read the content of sub directories as well.
This is what you have to do. Before going to write please refer the File class in java. This will help you to clear lot of things.
Below is the snippet that provides the list of files.
File directory = new File(path);
File[] listFiles = directory.listFiles();
if (listFiles != null) {
for (File file : listFiles) {
if (file.isDirectory())
// do the stuff what you need
else if (file.isFile()) {
// do the stuff what you need
}
}
}
}
Following code will give you list of files in android sdcard:
/**
* Return list of files from path. <FileName, FilePath>
*
* #param path - The path to directory with images
* #return Files name and path all files in a directory, that have ext = "jpeg", "jpg","png", "bmp", "gif"
*/
private List<String> getListOfFiles(String path) {
File files = new File(path);
FileFilter filter = new FileFilter() {
private final List<String> exts = Arrays.asList("jpeg", "jpg",
"png", "bmp", "gif");
#Override
public boolean accept(File pathname) {
String ext;
String path = pathname.getPath();
ext = path.substring(path.lastIndexOf(".") + 1);
return exts.contains(ext);
}
};
final File [] filesFound = files.listFiles(filter);
List<String> list = new ArrayList<String>();
if (filesFound != null && filesFound.length > 0) {
for (File file : filesFound) {
list.add(file.getName());
}
}
return list;
}
You can call same method to get sub directory file also.

how to browse only text files from my application

i have built an application,where i am supposed to browse only for txt files in the device and read it.but i am not getting a valid solution to it.Like for example if we take whatsapp,there you can browse different files under different headings like under videos you will only browse videos and under gallery you will only browse images.but whats in case for text files only?is there any way?Please suggest.
try this.
//for example your folder present in sdcard/cts.
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/cts");
for (File wavfile : f.listFiles(new FileExtensionFilter()))
{
String str = wavfile.getName().toString();
}
//create a class and the filter based on your need file extension
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".txt") || name.endsWith(".TXT") );
}
}
thank you.
I would put your directories your searching into arrays... Loop the arrays and look for the file extensions after the " . " if its not a text extension remove it. Then display the new array to user like the photo gallery works or however else you would want to represent them.
Note- If you need access to these later you may want to be saving the path if the user say...needs to click and open them...
you may be able to use something to this effect for searching the SD Card
File file[] = Environment.getExternalStorageDirectory().listFiles();
file[i].getAbsolutePath();
Then search it for the extensions you want...
This will give you a file manager as you like. Just needs a bit of work around. But definitely helps
//fill method is to get the dir
private void fill(File f)
{
File[] dirs = f.listFiles();
this.setTitle("Current Dir: " + f.getName());
List<Option> dir = new ArrayList<Option>();
List<Option> fls = new ArrayList<Option>();
try
{
for (File ff : dirs)
{
if (ff.isDirectory())
{
dir.add(new Option(ff.getName(), "Folder", ff.getAbsolutePath()));
}
else
{
String filetype[] = objOption.getName().split("\\.");
if (filetype[(filetype.length) - 1].equals("txt")) {
fls.add(new Option(ff.getName(), "File Size: "+ ff.length()+" bytes", ff.getAbsolutePath()));
}
}
}
}
catch (Exception e)
{}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if (!f.getName().equalsIgnoreCase("sdcard"))
{
dir.add(0, new Option("..", "Parent Directory", f.getParent()));
}
adapter = new FileArrayAdapter(FileChooser.this, R.layout.dialog_file_view,dir);
lvFileList.setAdapter(adapter);
}

How to rename folder of SD-Card from list-view in android

I am trying get all the list of particular folder name from SD-Card to list-view in android. I am giving two option to user they can create folder as well as they can rename folder from application it self.
With the list-view i have given check-box so user can check any single list value at a time and then can perform operation as they want of editing or creating folder in SD-Card.
Everything is working fine till creating folder, but my problem start's here, when user tries to rename folder name, then first time user can successfully changes the folder name but while doing same task second time, user is not able to rename same folder again.
What mistake i am doing, following is my code please help, Thanks in advance.
private static List<String> myList = new ArrayList<String>();
public static void folder_create() {
if (Code.pm == 1) {
String updateFolder = Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/";
File filecall = null;
filecall = new File(updateFolder);
File list[] = filecall.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String mUpdateName = myList.get(i);
File file = new File(updateFolder + "/" + mUpdateName);
System.out.println("=======File======" + file);
File file2 = new File(updateFolder + "/" + Code.className);
System.out.println("=======File2======" + file2);
file.renameTo(file2);
}
} else {
String filepath = Environment.getExternalStorageDirectory()
.getPath();
File file = new File(filepath, "/AudioRecorder/" + Code.className);
if (!file.exists()) {
file.mkdirs();
}
}
}
Here Code is static class and pm is integer variable. So when user click button based on pm variable value it will perform task weather to rename folder or create folder.
If I understand your issue, you're trying to rename a directory after having made 'some tasks'. Are those tasks made into this folder? If yes, be sure that you have closed your streams (creating / modifying content) like so:
stream.close();
Please also check the LogCat to see if some warnings are shown.

Path to screenshots in Android

Is there a way to find out the path used by android to save screenshots?
Can I get the path from a code?
Android's API has no fixed path for screenshots but
File pix = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File screenshots = new File(pix, "Screenshots");
might work. That's what ICS uses as path.
The "Screenshots" value is part of the private API.
Here is link to the source code where the value is set. Since the class is loaded in our application context there is no option to access the field. I'd hardcode it as #zapi suggested.
Few might find this usefull..
public static File mDir= new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)));
public static File mDirScreenshots = new File(mDir,"Screenshots");
And to fetch the screenshots
public static ArrayList<File> getAllScreenshots(File dir){
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
Log.e(YOUR_TAG, "getAllScreenshots: " + i + listFile[i].getName());
mScreenshotsFiles.add(listFile[i]);
}
}
return mScreenshotsFiles;
}
Recursion is your friend here.
Tested on Android version 9 and 12. Works good.
final String findThisDirectory = "screenshots";
final String rootPath = Environment.getExternalStorageDirectory().getPath();
//we do not want to include 'Android' directory because looking inside it
//or some directories inside of it can and will cause crash in some Android versions due to permissions related issues
String ignoreThisDirectory = "android";
void getPathRecursively(String rootPath, String matchThisDirectory, String ignoreThisDirectory){
File[] filesArray = new File(rootPath).listFiles();
if(filesArray.length > 0){
for(File file: filesArray){
if(file.isDirectory()){
if(file.getName().toLowerCase().equals(ignoreThisDirectory)){
continue;
}
else if(file.getName().toLowerCase().equals(matchThisDirectory)){
// here you found the path to 'screenshots' in file object
// get it from the file.getAbsolutePath()
break;
}
getPathRecursively(file.getAbsolutePath(), matchThisDirectory, ignoreThisDirectory);
}
}
}
}

Categories

Resources