java Android:空指针异常(文件)
我正在尝试制作一个应用程序,为此我需要列出文件。我找到了一些有用的代码,并根据我的需要进行了一些修改。这是我的(简单)代码:
// List all files from specific directory
public void listFiles(){
// Path to directory to scane
String path = Environment.getExternalStorageDirectory().toString()+"/Download/";
// New file-instance
File f = new File(path);
// Get the textview to display message
TextView textview = (TextView) findViewById(R.id.textView);
textview.setText(f.toString());
// List the files
File file[] = f.listFiles();
for(int i = 0; i < file.length; i++){
Log.d("Files", "Filename: " + file[i].getName());
}
}
我知道这是由文件引起的。我的for循环中的长度,但我不明白为什么会出现这个错误,因为它会抓取正确目录中的文件,而我在该目录中有文件
E
dit: This is my stack trace
java.lang.NullPointerException: Attempt to get length of null array
at com.example.filemaker.MainActivity.listFiles(MainActivity.java:79)
at com.example.filemaker.MainActivity$1.onClick(MainActivity.java:31)
at 安卓.view.View.performClick(View.java:4780)
at 安卓.view.View$PerformClick.run(View.java:19866)
at 安卓.os.Handler.handleCallback(Handler.java:739)
at 安卓.os.Handler.dispatchMessage(Handler.java:95)
at 安卓.os.Looper.loop(Looper.java:135)
at 安卓.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:698)
# 1 楼答案
那么NPE是哪条线呢?档案。长 这意味着该文件为空, 查看文件javadoc,我们可以在listFiles方法return中看到以下描述:
你的路径似乎无效