I'm new to programming Android, and I want to delete Files on the sd-card. This is my current (working) code...
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "ApplifierVideoCache");
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
Now I want to delete multiple files, but dont want to mention each file with that big block. Am I able to combine all files in one variable? Thanks ;)
Make a recursive method:
/*
* NOTE: coded so as to work around File's misbehaviour with regards to .delete(),
* which does not throw an exception if it fails -- or why you should use Java 7's Files
*/
public void doDelete(final File base)
throws IOException
{
if (base.isDirectory()) {
for (final File entry: base.listFiles())
doDelete(entry);
return;
}
if (!file.delete())
throw new IOException ("Failed to delete " + file + '!');
}
Another possibility would be using the Apache commons-io library and calling
if (file.isDirectory())
FileUtils.deleteDirectory(File directory);
else {
if(!file.delete())
throw new IOException("Failed to delete " + file);
}
You should make a method out of this chunk of code, pass file name and call it whenever you like:
public void DeleteFile(String fileName) {
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), fileName);
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
}
File dir = new File(android.os.Environment.getExternalStorageDirectory(),"ApplifierVideoCache");
Then call
deletedir(dir);
public void deletedir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
listFile[i].delete();
}
}
}
or if your folder as sub folders then
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++)
{
if (listFile[i].isDirectory())
{
walkdir(listFile[i]);
} else
{
listFile[i].delete();
}
}
}
For kotlin
Create a array of path list
val paths: MutableList<String> = ArrayList()
paths.add("Yor path")
paths.add("Yor path")
.
.
delete file for each path
try{
paths.forEach{
val file = File(it)
if(file.exists(){
file.delete()
}
}
}catch(e:IOException){
}
Related
please help me this code, I don't know how android manage files & folders
I use a function that get the list of files documents in android storage, but after check each file, that result illegal, exception throw: No such file or directory
**public void doJob() {
Log.d(TAG, "Check01952039847501: " + mListFileInput.size());
// list 27 files input
for (int i = 0; i < mListFileInput.size(); i++) {
File file = new File(mListFileInput.get(i));
Log.d(TAG, "Check010684946823046 = " + file);
// /storage/0F37-7BF9/aliasBook2/Da-Vinci.epub
Log.d(TAG, "Check010684946823046: check file: " + file.exists());
// false
try {
ZipFile zipFile = new ZipFile(file);
} catch (IOException e) {
e.printStackTrace();
// Exception throw "such file or directory android", all files
}
}
}**
Note: To get that mListFileInput list, I use recuisive function this:
**public void recuisiveGetEbook(File directory) {
File[] fileList = directory.listFiles();
if (fileList != null) {
for (int i = 0; i < fileList.length; i++) {
File file = fileList[i];
if (!file.getPath().contains("/Android")
&& !file.getPath().contains("/data")
&& !file.isHidden()) {
// if that is file
if (file.isFile() && file.exists() && file.canRead()) {
if (file.getName().endsWith(".epub")) {
lstResult.add(fileList[i].getPath());
Log.d(TAG, "Check019252357: " + fileList[i].getPath());
}
} // if that is folder
else recuisive1(fileList[i]);
}
}
}
}**
Ok, so I have a folder with about 2000 pictures, all with weird names, I would like to loop through the whole thing, and rename them to "something" + the number(i in the for loop). Is there anyway to rename a file when you only know the place in the directory and not the name. I guess the main problem is getting the name of the file at index x in a directory, is there anyway to do this?
public class stuff {
static ArrayList<File> images = new ArrayList<>();
public static void main(String[] args) throws IOException{
Files.walk(Paths.get("C:\\Users\\Seth Gower\\Pictures\\Stuff for imgur\\iFunny Dumps\\iFunny Dump (All)"))
.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
images.add(new File(filePath.toString()));
}
});
for(File x : images)
System.out.println(x.getName());
for (int i = 0; i < images.size(); i ++){
System.out.println(images.get(i).renameTo(new File(
"C:\\Users\\Seth Gower\\Pictures\\Stuff for imgur\\iFunny Dumps\\iFunny Dump (All)" + "\\" + "ifunnyDump" + i)));
}
}
}
static ArrayList<File> images = new ArrayList<>();
public static void main(String[] args) throws IOException{
Files.walk(Paths.get("path")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
images.add(new File(filePath.toString()));
}
});
for (int i = 0; i < images.size(); i ++){
images.get(i).renameTo(new File("path" + "\\" + "text" + i + ".jpg"));
}
}
This worked, thanks to #hexafraction and #MatthewStrawbridge
This is really simple
you need to first find the directory your files are located in
File dir = new File("C:\\yourdirectory");
now you need to loop through every file in the directory an rename it. A for each loop would be best. If you want before the loop you can check if the directory you specified is really a directory with
if (dir.isDirectory())
int i = 0;
for (File f : dir.listFiles()) {
try {
f.renameTo("YourText_"+i+".jpg");
i++;
}
catch (Exception e)
{
System.out.println(e);
}
}
This code works fine on android 4.4, 5.0, 5.1 , 6.0
File file = new File("/storage/emulated/0//Videos/");
String[] myFiles;
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
myFile.delete();
}
But when i use this for android 4.0, 4.1, 4.2 i get java.lang.NullPointerException referring at line
for (int i = 0; i < myFiles.length; i++)
So i try to initialize the String,
String[] myFiles = new String[100] //just big value
But android studio shows initializer "new String[100]" is redundent and error is not resolved.
Why does this happen?
Thanks..!
The javadoc for File.list() says that it can return null. You should always check for this whenever you call it and handle it correctly unless you are absolutely certain it will not return null.
This is because you are not checking your folder is null or not make sure your directory contains file
File file = new File("/storage/emulated/0//Videos/");
String[] myFiles;
if (file == null) {
} else {
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
if(myFile.exists())
myFile.delete();
}
}
And if you want to delete whole directory than you can use this sample method
public void deleteDirectory(File file) {
if( file.exists() ) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
file.delete();
}
}
public void Process(File aFile) throws IOException, ParseException {
if(aFile.isFile())
{
System.out.println("File name:"+aFile.getAbsolutePath());
}
else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles((FileFilter) HiddenFileFilter.HIDDEN);
if(listOfFiles!=null) {
for (int i = 0; i < listOfFiles.length; i++)
Process(listOfFiles[i]);
}
File[] listOfFiles1 = aFile.listFiles((FileFilter) HiddenFileFilter.VISIBLE);
if(listOfFiles1!=null) {
for (int i = 0; i < listOfFiles1.length; i++)
Process(listOfFiles1[i]);
}
}
}
Call the function in main as follows
String nam = "E:\\";
File aFile = new File(nam);
Process(aFile);
I am using the above code to retrieve all the file details which is present in E:\. It does not retrieve the hidden folder file details. Can anyone help on this?
Just use aFile.listFiles() without any FileFilter then put path of each hidden folder in a list based on check on isHidden().
Sample code:
public static void process(File aFile){
if (aFile.isFile()) {
System.out.println("File name:" + aFile.getAbsolutePath());
} else if (aFile.isDirectory()) {
if(aFile.isHidden()){
System.out.println(aFile.getAbsolutePath()+"folder is hidden");
}
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++)
process(listOfFiles[i]);
}
}
}
here is a simple function that searches for a file in a given folder and its subfolders i am able to find the file but somehow the return value is a null and can someone also explain what happens in the stack when we use recursive functions if you can relate it to my scenario it would be great...
File getFileInFolder(File folder, String fileName) {
//System.out.println(" PathTo : "+folder.getAbsolutePath());
File [] files = folder.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
return getFileInFolder(files[i],fileName);
} else {
//System.out.println(" file : "+files[i].getName());
if (files[i].getName().equals(fileName)) {
System.out.println(" Found file : "+files[i].getName());
return files[i];
}
}
}
}
return null;
}
Let's say that you're looking for a.txt in the following folder:
root
sub1
b.txt
sub2
a.txt
What your algorithm does is
List the files in root. That returns sub1 and sub2.
Iterate through the files. If the file is a directory, return the result of the method on this directory
So, the algorithm will search only in sub1, and that will return null.
You need to continue searching in other directories if the file wasn't found in the first one:
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
File resultForSubDirectory = getFileInFolder(files[i], fileName);
if (resultForSubDirectory != null) {
return resultForSubDirectory;
} // else: continue looping
}
else {
...
}
}
i have solved it using a bool variable filefound and i break all the loops in the stack, don"t know if it is the best way to do it but it works for me
boolean filefound = false;
File getFileInFolder(File folder, String fileName) {
filefound = false;
//System.out.println(" PathTo : "+folder.getAbsolutePath());
File [] files = folder.listFiles();
File file = null;
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
file = getFileInFolder(files[i],fileName);
if(filefound) {
file= files[i];
break;
}
} else {
//System.out.println(" file : "+files[i].getName());
if (files[i].getName().equals(fileName)) {
System.out.println(" Found file : "+files[i].getName());
file= files[i];
filefound = true;
break;
}
}
}
}
return file;
}