How to get list of only directories android - android

I have good working android list, and i need only directories to show.
I tried some ways but it doesn`t event do a thing.
Using isDirectory() method and I think I am using it not that way.
private String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
path = Environment.getExternalStorageDirectory().toString();
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
// Read all files sorted into the values-array
List<String> values = new ArrayList();
File dir = new File(path);
if (!dir.canRead()) {
setTitle(getTitle() + " (inaccessible)");
}
String[] list = {};;
if (new File(path).isDirectory() == true) {
list = dir.list();
} else {return;}
if (list != null) {
for (String file : list) {
if ( new File(path).isDirectory() == true) { // !file.startsWith(".") &&
values.add(file);
} else {return;}
}
}
Collections.sort(values);
// Put the data into the list
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_2, android.R.id.text1, values);
setListAdapter(adapter);
}

Try something like this
File f = new File(path);
//list files
File[] filesList = f.listFiles(); //Returns an array of files contained in the directory represented by this file.
//iterate list of files
for (File inFile : files) {
if (inFile.isDirectory()) {
// Check is directory
}
}

Related

Android clearing app cache clears provider also

I used following code to delete my app cache.
public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}
public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}
return deletedAll;
}
Once I delete the code means it deletes the provider which I declared in manifest. Is there any way to clear cache without deleting content provider?
You can avoid this by not deleting database folder
if (!fileName.equals("lib")&&!fileName.equals("files")&&!fileName.equals("database")) {
deleteFile(new File(applicationDirectory, fileName));
}

Displaying folders only containing files with certain file type

I have set up code to display all folders that are on the SD card but now I am trying to figure out how to only display folders which contain MP3 files.
How can I filter out the folders that don't contain .MP3 files? thanks.
class:
public class FragmentFolders extends ListFragment {
private File file;
private List<String> myList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
File temp_file = new File(file, myList.get(position));
if (!temp_file.isFile()) {
file = new File(file, myList.get(position));
File list[] = file.listFiles();
myList.clear();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
Toast.makeText(getActivity(), file.toString(), Toast.LENGTH_LONG)
.show();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
return;
}
}
You can check if the files within a directory are mp3 files before adding to your list view's dataset
Modify your code as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
//list content of root sd
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
//check the contents of each folder before adding to list
File mFile = new File(file, list[i].getName());
File dirList[] = mFile.listFiles();
if(dirList == null) continue;
for (int j = 0; j < dirList.length; j++) {
if(dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".mp3")){
myList.add(list[i].getName());
break;
}
}
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList));
}
I tested this and it works. Only caveat is, it doesn't check for sub-directories.
So in:
sdcard/Music/mistletoe.mp3
sdcard/Media/Tracks/mistletoe.mp3
only the Music folder will be listed.
Also, you may want to use an asyncTask to eschew hogging the UI thread
You can user a fileNameFilter and filter out the folders/files you don't want.
File baseDirectory = new File("/mnt/sdcard/"); //Your base dir here
File[] files = baseDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String fileName) {
File possibleMp3Folder = new File(dir, fileName);
if (possibleMp3Folder.isDirectory()) {
File[] files1 = possibleMp3Folder.listFiles();
for (File file : files1) {
if (file.getName().toLowerCase().endsWith(".mp3")) {
return true;
}
}
}
return false;
}
});
If you are looking for all folders contains mp3 files (both on Internal storage and SD Card) and available storages contains media:
Initialize two Sets for media storage paths and mp3 folders paths:
private HashSet<String> storageSet = new HashSet<>();
private HashSet<String> folderSet = new HashSet<>();
Get both in one method (you can return value if you need only one):
private void getMediaFolders() {
ContentResolver resolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = { MediaStore.Audio.Media.DATA };
Cursor cursor = resolver.query(uri, projection, selection, null, null);
if(cursor != null && cursor.getCount() > 0) {
int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
while(cursor.moveToNext()) {
String data = cursor.getString(dataIndex);
int i = 0;
for (int slashCount = 0; i < data.length(); i++) {
if (data.charAt(i) == '/' && ++slashCount == 3) {
storageSet.add(data.substring(0, i));
break;
}
}
if (data.toLowerCase().endsWith("mp3")) {
int lastSlashIndex = data.lastIndexOf('/');
while (i < lastSlashIndex) {
data = data.substring(0, lastSlashIndex);
folderSet.add(data);
lastSlashIndex = data.lastIndexOf('/');
}
}
}
}
if (cursor != null) { cursor.close(); }
}
Filter folders (with Annimonstream):
private ArrayList<File> getFilteredFolders(#NonNull String path, HashSet<String> folderSet) {
File[] filesList = new File(path).listFiles();
if (filesList == null) { return new ArrayList<>(); } // Or handle error as you wish
return Stream.of(filesList)
.filter(File::isDirectory)
.filter(f -> folderSet.contains(f.getAbsolutePath()))
.collect(Collectors.toCollection(ArrayList::new));
}
Show storages (if needed).
Uri,Projection,
MediaStore.Video.Media.DATA
+ " like " + "'%.mp4%'"
+ " AND "
+ MediaStore.Video.Media.DATA
+ " like " + "'%" + getResources().
getString(R.string.string_store_video_folder)
+"%'", null,
MediaStore.Video.Media.DATE_MODIFIED
this will give mp4 files in a specific folder

List of files in assets folder and its subfolders

I have some folders with HTML files in the "assets" folder in my Android project. I need to show these HTML files from assets' sub-folders in a list. I already wrote some code about making this list.
lv1 = (ListView) findViewById(R.id.listView);
// Insert array in ListView
// In the next row I need to insert an array of strings of file names
// so please, tell me, how to get this array
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filel));
lv1.setTextFilterEnabled(true);
// onclick items in ListView:
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
//Clicked item position
String itemname = new Integer(position).toString();
Intent intent = new Intent();
intent.setClass(DrugList.this, Web.class);
Bundle b = new Bundle();
//I don't know what it's doing here
b.putString("defStrID", itemname);
intent.putExtras(b);
//start Intent
startActivity(intent);
}
});
private boolean listAssetFiles(String path) {
String [] list;
try {
list = getAssets().list(path);
if (list.length > 0) {
// This is a folder
for (String file : list) {
if (!listAssetFiles(path + "/" + file))
return false;
else {
// This is a file
// TODO: add file name to an array list
}
}
}
} catch (IOException e) {
return false;
}
return true;
}
Call the listAssetFiles with the root folder name of your asset folder.
listAssetFiles("root_folder_name_in_assets");
If the root folder is the asset folder then call it with
listAssetFiles("");
try this it will work in your case
f = getAssets().list("");
for(String f1 : f){
Log.v("names",f1);
}
The above snippet will show the contents of the asset root.
For example... if below is the asset structure..
assets
|__Dir1
|__Dir2
|__File1
Snippet's output will be ....
Dir1 Dir2 File1
If you need the contents of the Directory Dir1
Pass the name of Directory in the list function.
f = getAssets().list("Dir1");
Hope This Help:
following code will copy all the folder and it's content and content of sub folder to sdcard location:
private void getAssetAppFolder(String dir) throws Exception{
{
File f = new File(sdcardLocation + "/" + dir);
if (!f.exists() || !f.isDirectory())
f.mkdirs();
}
AssetManager am=getAssets();
String [] aplist=am.list(dir);
for(String strf:aplist){
try{
InputStream is=am.open(dir+"/"+strf);
copyToDisk(dir,strf,is);
}catch(Exception ex){
getAssetAppFolder(dir+"/"+strf);
}
}
}
public void copyToDisk(String dir,String name,InputStream is) throws IOException{
int size;
byte[] buffer = new byte[2048];
FileOutputStream fout = new FileOutputStream(sdcardLocation +"/"+dir+"/" +name);
BufferedOutputStream bufferOut = new BufferedOutputStream(fout, buffer.length);
while ((size = is.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, size);
}
bufferOut.flush();
bufferOut.close();
is.close();
fout.close();
}
Here is a solution to my problem that I found out working 100% listing all directories and files even sub-directories and files in subdirectories.
Note: In my case
Filenames had a . in them. i.e. .htm .txt etc
Directorynames did not have any . in them.
listAssetFiles2(path); // <<-- Call function where required
//function to list files and directories
public void listAssetFiles2 (String path){
String [] list;
try {
list = getAssets().list(path);
if(list.length > 0){
for(String file : list){
System.out.println("File path = "+file);
if(file.indexOf(".") < 0) { // <<-- check if filename has a . then it is a file - hopefully directory names dont have .
System.out.println("This is a folder = "+path+"/"+file);
listAssetFiles2(file); // <<-- To get subdirectory files and directories list and check
}else{
System.out.println("This is a file = "+path+"/"+file);
}
}
}else{
System.out.println("Failed Path = "+path);
System.out.println("Check path again.");
}
}catch(IOException e){
e.printStackTrace();
}
}//now completed
Thanks
i think that this is best that check file is dir or not, altarnative try,catch!
public static List<String> listAssetFiles(Context c,String rootPath) {
List<String> files =new ArrayList<>();
try {
String [] Paths = c.getAssets().list(rootPath);
if (Paths.length > 0) {
// This is a folder
for (String file : Paths) {
String path = rootPath + "/" + file;
if (new File(path).isDirectory())
files.addAll(listAssetFiles(c,path));
else files.add(path);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return files;
}
Based on the #Kammaar answer. This kotlin code scans the file tree for the leafs:
private fun listAssetFiles(path: String, context: Context): List<String> {
val result = ArrayList<String>()
context.assets.list(path).forEach { file ->
val innerFiles = listAssetFiles("$path/$file", context)
if (!innerFiles.isEmpty()) {
result.addAll(innerFiles)
} else {
// it can be an empty folder or file you don't like, you can check it here
result.add("$path/$file")
}
}
return result
}
This method return file names in a directory in Assets folder
private fun getListOfFilesFromAsset(path: String, context: Context): ArrayList<String> {
val listOfAudioFiles = ArrayList<String>()
context.assets.list(path)?.forEach { file ->
val innerFiles = getListOfFilesFromAsset("$path/$file", context)
if (innerFiles.isNotEmpty()) {
listOfAudioFiles.addAll(innerFiles)
} else {
// it can be an empty folder or file you don't like, you can check it here
listOfAudioFiles.add("$path/$file")
}
}
return listOfAudioFiles
}
For example you want to load music file path from sound folder
You can fetch all sound like this:
private const val SOUND_DIRECTORY = "sound"
fun fetchSongsFromAssets(context: Context): ArrayList<String> {
return getListOfFilesFromAsset(SOUND_DIRECTORY, context)
}
public static String[] getDirectoryFilesRecursive(String path)
{
ArrayList<String> result = new ArrayList<String>();
try
{
String[] files = Storage.AssetMgr.list(path);
for(String file : files)
{
String filename = path + (path.isEmpty() ? "" : "/") + file;
String[] tmp = Storage.AssetMgr.list(filename);
if(tmp.length!=0) {
result.addAll(Arrays.asList(getDirectoryFilesRecursive(filename)));
}
else {
result.add(filename);
}
}
}
catch (IOException e)
{
Native.err("Failed to get asset file list: " + e);
}
Object[] objectList = result.toArray();
return Arrays.copyOf(objectList,objectList.length,String[].class);
}

Access the file browser and get the path of file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android File Picker
I need to include a file chooser that returns me the full file path of the selected file, in my Android App.
But I have no idea of How I could implement this.
I have yet looking for this question in Stackoverflow but I haven't find a clear answer to my question.
I have find how to get filePath from images in the Gallery but nothing about a way to get the filePath of also all others file type.
private List<String> FindFiles(Boolean fullPath) {
final List<String> tFileList = new ArrayList<String>();
String[] fileTypes = new String[]{"dat","doc","apk"....}; // file extensions you're looking for
FilenameFilter[] filter = new FilenameFilter[fileTypes .length];
int i = 0;
for (final String type : fileTypes ) {
filter[i] = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("." + type);
}
};
i++;
}
FileUtils fileUtils = new FileUtils();
File[] allMatchingFiles = fileUtils.listFilesAsArray(
new File("/sdcard"), filter, -1);
for (File f : allMatchingFiles) {
if (fullPath) {
tFileList.add(f.getAbsolutePath());
}
else {
tFileList.add(f.getName());
}
}
return tFileList;
}
public class FileUtils {
public File[] listFilesAsArray(File directory, FilenameFilter[] filter,
int recurse) {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
public Collection<File> listFiles(File directory,
FilenameFilter[] filter, int recurse) {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
if (entries != null) {
for (File entry : entries) {
for (FilenameFilter filefilter : filter) {
if (filter == null
|| filefilter
.accept(directory, entry.getName())) {
files.add(entry);
Log.v("FileUtils", "Added: "
+ entry.getName());
}
}
if ((recurse <= -1) || (recurse > 0 && entry.isDirectory())) {
recurse--;
files.addAll(listFiles(entry, filter, recurse));
recurse++;
}
}
}
return files;
}
}

List all the files from all the folders in a single list

I am looking for the solution to list all the files from root/Android device.
Suppose there are three folders inside the root directory, but I want to display all the files in all of these folders in a single list...
Now if am using
File f = new File("/sdcard");
Then it will list all the files from the sdcard folder only... And if I will use
File f = new File("/download");
Then it will list all the files from download folder only ..and if I will use
File f = new File("/");
Then it will list only the root directory files...not the files inside /sdcard or /download.
So what steps shall I follow to list all the files with a filter to list only .csv files from all the folder inside root?
Try this:
.....
List<File> files = getListFiles(new File("YOUR ROOT"));
....
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
}
Or a variant without recursion:
private List<File> getListFiles2(File parentDir) {
List<File> inFiles = new ArrayList<>();
Queue<File> files = new LinkedList<>();
files.addAll(Arrays.asList(parentDir.listFiles()));
while (!files.isEmpty()) {
File file = files.remove();
if (file.isDirectory()) {
files.addAll(Arrays.asList(file.listFiles()));
} else if (file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
return inFiles;
}
I've modified Vyacheslav's solution because I needed only file names inside the directory.
...
List<String> files = getList(new File("YOUR ROOT"));
...
private List<String> getList(File parentDir, String pathToParentDir) {
ArrayList<String> inFiles = new ArrayList<String>();
String[] fileNames = parentDir.list();
for (String fileName : fileNames) {
if (fileName.toLowerCase().endsWith(".txt") || fileName.toLowerCase().endsWith(".rtf") || fileName.toLowerCase().endsWith(".txd")) {
inFiles.add(pathToParentDir + fileName);
} else {
File file = new File(parentDir.getPath() + "/" + fileName);
if (file.isDirectory()) {
inFiles.addAll(getList(file, pathToParentDir + fileName + "/"));
}
}
}
return inFiles;
}
You can use the following method,
private int readLogList(String filePath)
{
File directory = Environment.getExternalStorageDirectory();
File folder = new File(directory + ConstantCodes.FILE_SEPARATOR + filePath);
if (!folder.exists())
{
return 0;
}
return folder.list().length;
}

Categories

Resources