android string array nullpointerexception on older android versions - java

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();
}
}

Related

How to retrieve hidden folders using java?

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]);
}
}
}

Return values in recursive function in java

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;
}

Deleting Multiple Files Java (Android)

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){
}

Readin from /data/dalvik-cache JavaNullPointer

I'm trying to list all files in /data/dalvik-cache folder but i keep getting NullPointerException
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
File folder = new File(dir);
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName() );
}
}
The array dalvikPath contains /data/dalvik-cache
I request su before trying to list and I think i have all the permissions in my manifest.
I think you need to check directory is exist or not . then you can get list of files
File folder = new File(dir);
if(folder.exists()){
File list[] = folder.listFiles();
if(list.length>0{
for( int i=0; i< list.length; i++){
}
}
}else{
}
Ok so i've modified my code and now i don't have javanullpointer but i don't "find" an files in the folders...
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
log.append("Reading " + dir + "\n");
File folder = new File(dir);
if (folder.exists() && folder.isDirectory()){
try{
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName().toString() );
log.append(list[i].getName().toString() +"\n");
}
}
catch ( Exception e) {
}
}
else {
log.append("Folder " + dir + "doesn't exist.\n");
}

How to change names of files in String[]

I have such code...
File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
String[] files = fileDir.list();
So, I have an array of files' names...
But I want to GET an array of "path to each file"+fileDir.list()
For example
I have - "/09.jpg"
I want - "/mnt/sdcard/dd/09.jpg"
How can I do it? Thanks
try following code,
String path = "/mnt/sdcard/dd";
File fileDir = new File( path );
if(!fileDir.exists() || !fileDir.isDirectory())
{
return;
}
String[] files = fileDir.list();
for ( int i = 0 ; i < files.length ; i++ )
{
files[i] = path + "/" + files[i];
}
Now the array files contains the updated value with path.
File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
File[] files = fileDir.listFiles();
for(File f: files){
Log.i("", f.getAbsolutePath());
}
What you need is getAbsolutePath(),
File file = new File("/mnt/sdcard/dd");
Files[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
Log.e("Root Path of file:" + i, files[i].getAbsolutePath());
}

Categories