Problem :
I want to delete video file from android device's internal storage.
Below code is in class that extends BaseAdapter and "file.delete()" method returns false
File fdelete = new File(videolist.get(position).getVideopath());
Log.d(TAG,"Path to delete : "+videolist.get(position).getVideopath());
if (fdelete.exists()) {
Log.d(TAG,"DELETE EXIST");
if (fdelete.delete()) {
Log.d(TAG,"DELETED");
} else {
Log.d(TAG,"NOT DELETED");
}
}
" videolist.get(position).getVideopath() " returns this : "/storage/emulated/0/Download/jellyfish-3-mbps-hd-h264xgdhdudtudutdutdjtditditdtidjtditdjtdtkd.mkv"
Try this
private void deleteMedia(final String advName) {
File path = Environment.getExternalStorageDirectory();
File directory = new File(path.getAbsolutePath() + "/your directory name");
File[] files = directory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.contains(advName);
}
});
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
file.delete();
}
}
}
Related
I want to filter files stored in my phone with the .apk extension. I have tried the below code but it filters files found only in sdcard/file.apk
but I want it to filter the file by searching into the sub directories of sdcard also.
For example if there is an apk file inside sdcard/download/mm.apk it should filter it and also if there is another file in sdcard/New Folder/ABC/cc.apk it should filter it too.
How can I do that? thank you for your help...
ExtFilter apkFilter = new ExtFilter("apk");
File file[] =Environment.getExternalStorageDirectory().listFiles(apkFilter);
Log.i("InstallApk","Filter applied. Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.i("InstallApk",
"FileName:" + file[i].getName());
}
ArrayAdapter af=new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1,android.R.id.text1,file);
ListView ll=(ListView) findViewById(R.id.mainListView1);
ll.setAdapter(af);
}
class ExtFilter implements
FilenameFilter {
String ext;
public ExtFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext);
}
}
You have to do it recursively. It is not enough to check for the extension, you must also verify that it is a regular file cos I can as well name a directory dir.apk. Verifying that it is a regular file is also not enough since one can name any file with any extension. Regardless, checking that it is a regular file should be enough without consideration of the intended action on these files.
public void someFunction() {
List<File> apkFiles = getApkFiles(Environment.getExternalStorageDirectory(), new ApkSearchFilter());
File file[] = apkFiles.toArray(new File[apkFiles.size()]);
Log.i("InstallApk", "Filter app\"lied. Size: " + file.length);
for (File aFile : file) {
Log.i("InstallApk", "FileName:" + aFile.getName());
}
}
List<File> getApkFiles(File file, ApkSearchFilter filter) {
if (filter.isApk(file))
return Collections.singletonList(file);
else if (filter.isDirectory(file)) {
LinkedList<File> files = new LinkedList<>();
for (File subFile : file.listFiles()) {
files.addAll(getApkFiles(subFile, filter));
}
return files;
} else return Collections.emptyList();
}
class ApkSearchFilter implements FileFilter {
boolean isApk(File file) {
return !file.isDirectory() && file.getName().matches(".*\\.apk");
}
boolean isDirectory(File file) {
return file.isDirectory();
}
#Override
public boolean accept(File file) {
return isDirectory(file) || isApk(file);
}
}
This is one in many way you can try, don't forget to add permission in manifest:
private List<String> ReadSDCard()
{
File f = new File("your path"); // Environment.getExternalStorageDirectory()
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
String filePath = file.getPath();
if(filePath.endsWith(".apk"))
tFileList.add(filePath);
}
return tFileList;
}
Can anyone help me to skip file having extension "read" in my code ?
I have two files in my folder:
123.csv
123.csv.read
After execution every csv file is converted into ".csv.read", but if the same file comes again, that file should be skipped.
Like this file (123.csv.read) has been processed already, so if same new file(123.csv) comes, I want to be skipped that file.
In my code below, after 123.csv file is processed, the folder has only one file 123.csv.read. break is not behaving as I was expecting.
context.Str = ((String)globalMap.get("tFileList_1_CURRENT_FILEPATH"));
String extension = context.Str.substring(context.Str.lastIndexOf(".") + 1);
if (extension.equals("read"))
{
break;
}
else {
System.out.println("Good File to Process");
}
public static void listFile(final String folder, final String ext) {
ExtFilter filter = new ExtFilter(ext);
File dir = new File(folder);
if (dir.isDirectory() == false) {
System.out.println("Directory does not exists : " + FindFileExtension.FILE_DIR);
return;
}
// list out all the file name and filter by the extension
String[] list = dir.list(filter);
if (list.length == 0) {
System.out.println("no files end with : " + ext);
return;
}
for (String file : list) {
String temp = new StringBuffer(FindFileExtension.FILE_DIR).append(File.separator).append(file).toString();
System.out.println("file : " + temp);
// do your stuff here this file is not processed
}
}
public static class ExtFilter implements FilenameFilter {
private String ext;
public ExtFilter(final String ext) {
this.ext = ext;
}
public boolean accept(final File dir, final String name) {
return (name.endsWith(this.ext));
}
}
You can do something like that,it might help you
You can try this:
For example 123.csv file came again, then you check this if exist in read folder
if(!new File(123.csv+".read").exist()) {
// if this file is not exist, then it means that this has not been processed
// process the file
} else {
// do some other staff
}
Edit: Or you can try this
public static void main(String[] args) throws Exception {
File dir = new File("your_path");
File[] processedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().contains("read");
}
});
List<File> files = Arrays.asList(processedFiles);
File[] noneProcessedFiles = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return !pathname.getName().contains("read");
}
});
for (File file : noneProcessedFiles) {
if (!files.stream().findAny().get().getName().contains(file.getName())) {
// process the file....
System.out.println("Not found ... " + file.getName());
} else {
// do some other staff....
System.out.println("Fount the file");
}
}
}
I have a directory structure as follows:
DB_SET
-D1
- DB_1.txt
-D2
- DB_2.txt
-D3
- DB_3.txt
-D4
- DB_4.txt
-D5
- DB_5.txt
I want to store all DB_1.txt, DB_2.txt, DB_3.txt, DB_4.txt, DB_5.txt in an ArrayList. How can I do this?
My Partial code:
File folder = new File("./WebContent/datasets/DB_Set/");
File[] listOfFiles = folder.listFiles();
System.out.println("listofFiles: "+listOfFiles);
ArrayList<File> sub_dir = new ArrayList<File>();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
}
else if (listOfFiles[i].isDirectory()) {
sub_dir.add(listOfFiles[i]);
}
}
You need to go into 2 levels deep.
File folder = new File("./WebContent/datasets/DB_Set/");
File[] listOfSubDirectories = folder.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
});
ArrayList<File> filesList = new ArrayList<File>();
for (File dir : listOfSubDirectories) {
File[] files = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isFile();
}
});
for (File f : files) {
filesList.add(f);
}
}
Create a FileFilter that implements accept, something like
boolean accept(File pathname) {
returns pathname != null && pathname.isFile();
}
and then call listFiles() with the filter
File[] files = folder.listFiles(my_file_filter);
and files should contain only the files. If you need to make sure the file names all end with .txt (because there could be other files in the directories) then add a string check of the file name.
Another approach to this would be to accumulate the files recursively:
private static List<String> addFiles (File dir) {
List<String> result = new ArrayList<String>();
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
restult.addAll(addFiles(f));
} else if (f.isFile()) {
result.add(f.getName());
} else { // Just in case it's not a file or directory
// log or something
}
}
}
public static void main (String[] args) {
File folder = new File("./WebContent/datasets/DB_Set/");
List<File> files = addFiles(folder);
}
Here i have Folder(Books)in that i have 3 sub folders named:sub1, sub2, sub3 and sub1 have 2 files, sub2 have 3 files, sub3 have 4 files. And sub1.zip,sub2.zip and sub3.zip. I want to keep only zip files and delete sub1, sub2, sub3 folders of Books. With my code I'm able to delete all inside files of sub1 folder, sub2, sub3 finally all folders becoming empty, then how can I delete sub1,sub2 and sub3 folders.
public void SaveZipFiles(File destwithouAudio) throws IOException {
File[] listOfFiles = destwithouAudio.listFiles();
for (File listOfFile : listOfFiles) {
if (listOfFile.getName().endsWith(".zip")) {
} else {
File FolderInside = new File(listOfFile.getAbsolutePath());
File[] listOfFilesInside = FolderInside.listFiles();
for (File listOfFilesInside1 : listOfFilesInside) {
File deleteFolder = new File(listOfFilesInside1.getAbsolutePath());
//System.out.println(""+listOfFilesInside[j]);
RecursiveDelete(deleteFolder);
}
}
}
}
RecursiveDelete method code is:
public static void RecursiveDelete(File file) throws IOException {
if (file.isDirectory()) {
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
} else {
String files[] = file.list();
for (String temp : files) {
File fileDelete = new File(file, temp);
RecursiveDelete(fileDelete);
}
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
After deleting all files from sub1,sub2,sub3 foldersIi need to delete all sub1,sub2,sub3 folders.
Where to change the code?
public void deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete(); // The directory is empty now and can be deleted.
}
then, you could be using
public void SaveZipFiles(File destwithouAudio) {
File[] deletion = destwithouAudio.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return !name.endsWith(".zip");
}
});
for (File toDelete : deletion) {
deleteDir(toDelete);
}
}
(using deleting folder from java folder deletion)
public void checkfile (String serverName) throws Exception {
if (serverName == null)
serverName = "";
System.out.println("IN Check file method");
File folder = new File("D:\\MVXOUT412"); //Path on the server
int count = 0;
String abc;
File[] files = folder.listFiles();
if (files != null) {
System.out.println("IN IF method");
for (int i=0;i<files.length ;i++) {
count++;
abc = files[i].getName();
System.out.println("Number of files: " + count);
System.out.println("Name of files: " + abc);
}
}
}
This code is showing only some files at path/folder on the server. Other files can't be viewed. Login and logout happens successfully.
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);