如何列出目录中的文件?
我是 Android 开发新手,所以如果这是一件容易做的事情,请原谅我。
我想获取 SD 卡上目录中的所有文件并将它们显示在微调器中,但我只是不知道如何操作。 这就是我所拥有的,我什至不知道其中是否有任何好处。
//creates this directory if its not there??
File sd = new File("/sdcard/myfolder");
//gets a list of the files
File[] sdDirList = sd.listFiles();
//add them to the spinner array (this makes it crash)
for(int i=0;i<sdDirList.length;i++)
array_spinnerLoad[i] = sdDirList[i].getName();
那么我哪里错了? 任何地方都有易于使用的教程的有用链接吗? 它不一定是一个旋转器,只是我可以从中选择的一些列表,
谢谢:)
编辑: 它不会因此崩溃,但旋转器数组未填充
File[] sdDirList = sd.listFiles();
if (sdDirList != null)
{
array_spinnerLoad=new String[sdDirList.length];
for(int i=0;i<sdDirList.length;i++)
array_spinnerLoad[i] = sdDirList[i].getName();
}
im new to android development so please forgive me if this is an easy thing to do.
i want to get all the files in a directory on the sd card and display them in a spinner, but i just cant work out how.
this is what i have and i dont even know if any of it is any good.
//creates this directory if its not there??
File sd = new File("/sdcard/myfolder");
//gets a list of the files
File[] sdDirList = sd.listFiles();
//add them to the spinner array (this makes it crash)
for(int i=0;i<sdDirList.length;i++)
array_spinnerLoad[i] = sdDirList[i].getName();
so where am i going wrong?
any usefull link to an easy to use tutorial anywhere?
it doesnt have to be a spinner, just some list i can select from
thank you :)
edit:
it doesnt crash with this but the spinner array is not filled
File[] sdDirList = sd.listFiles();
if (sdDirList != null)
{
array_spinnerLoad=new String[sdDirList.length];
for(int i=0;i<sdDirList.length;i++)
array_spinnerLoad[i] = sdDirList[i].getName();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
/sdcard/myfolder
不存在或者不是目录,则listFiles
返回null
。你可能会因 NPE 而崩溃。您可以使用exists()
和isDirectory()
来诊断问题所在。 (另外,您可以测试sdDirList != null
。)PS 这将帮助您获得更准确的答案来发布有关崩溃的详细信息,例如异常。
If
/sdcard/myfolder
doesn't exist or is not a directory, thenlistFiles
returnsnull
. You're probably crashing with a NPE. You can useexists()
andisDirectory()
to diagnose what's wrong. (Plus, you can test thatsdDirList != null
.)P.S. It would help you to get more accurate answers to post details about the crash -- such as the exception.