Reputation: 1424
My aim is to get list of all mp3 files in my computer(below code in c: directory). But when I run this code, I am getting NullPointerException
. But works well for other directory like(e:).
public class music {
public static void main(String args[]){
extract("c:\\");
}
public static void extract(String p){
File f=new File(p);
File l[]=f.listFiles();
for(File x:l)
{
//System.out.println(x.getName());
if(x.isHidden()||!x.canRead())
continue;
if(x.isDirectory())
extract(x.getPath());
else if(x.getName().endsWith(".mp3"))
System.out.println(x.getPath()+"\\"+x.getName());
}
}
}
Upvotes: 1
Views: 2982
Reputation: 4917
In Windows operating system. C Drive (Windows drive) have system file that used by windows while running and some file that locked by windows. When your code try to access that files its through exception.
Try to run this code with other then C:// drive..
Add Try catch or null check for this files:
import java.io.*;
public class Music {
public static void main(String args[]){
extract("c:\\");
}
public static void extract(String p){
File f=new File(p);
File l[]=f.listFiles();
for(File x:l){
if(x==null) return;
if(x.isHidden()||!x.canRead()) continue;
if(x.isDirectory()) extract(x.getPath());
else if(x.getName().endsWith(".mp3"))
System.out.println(x.getPath()+"\\"+x.getName());
}
}
}
Upvotes: 0
Reputation: 124215
I got NPE with your code when it tried to access some not real directories like c:\Documents and Settings
.
To solve this problem you can skip iterating over directories that returns null
from listFiles()
like in this code:
public static void main(String args[]) {
extract(new File("c:\\"));
}
public static void extract(File dir) {
File l[] = dir.listFiles();
if (l == null) {
System.out.println("[skipped] " + dir);
return;
}
for (File x : l) {
if (x.isDirectory())
extract(x);
if (x.isHidden() || !x.canRead())
continue;
else if (x.getName().endsWith(".mp3"))
System.out.println(x.getPath());//name should be included in path
}
}
Upvotes: 2