我正在创建一个Android应用程序,我想列出目录中的文件.我是通过打电话来做的
File[] files = path.listFiles(new CustomFileFilter());
Run Code Online (Sandbox Code Playgroud)
path
是一个File
通过调用创建的对象
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Run Code Online (Sandbox Code Playgroud)
当我然后files
通过调用尝试获取数组的长度
int length = files.length;
Run Code Online (Sandbox Code Playgroud)
这行给了我一个NullPointerException
,因为files
是null.
我已经path
通过调用检查了我是否尝试列出存在的文件
System.out.println("Path exists: " + path.exists());
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序时,它会打印出来
Path exists: true
Run Code Online (Sandbox Code Playgroud)
在Android Studio控制台中,因此该目录存在.
我还打印了路径名称,即
/storage/emulated/0/Download
Run Code Online (Sandbox Code Playgroud)
所以这path
是一个目录,而不是一个文件.
我不知道为什么我会得到一个NullPointerException
,因为这path
是一个目录.
编辑:CustomFileFilter
该类看起来像这样:
public class CustomFileFilter implements FileFilter {
// Determine if the file should be accepted
@Override
public boolean accept(File file) {
// If the file isn't a …
Run Code Online (Sandbox Code Playgroud) 最近,我正在尝试将我的应用程序从 SDK-29 迁移到 SDK-30。我最关心的一件事是范围存储。
我在官方文档中看到“在 Android 11(API 级别 30)及更高版本上,应用程序无法在外部存储上创建自己的应用程序特定目录”。
因此,我尝试在外部存储中创建自己的目录并向其中写入一个新文件。代码如下所示:
// creating new directory under external storage
val appDir = File(applicationContext.getExternalFilesDir(null), "play")
appDir.mkdir()
// writing new file under my own directory
val newFile = File(appDir.absolutePath, "test.jpg")
val outputStream = FileOutputStream(newFile)
val inputStream = resources.openRawResource(R.drawable.ic_launcher_foreground)
val data = byteArrayOf()
inputStream.read(data)
outputStream.write(data)
inputStream.close()
outputStream.close()
Run Code Online (Sandbox Code Playgroud)
我预计这段代码会崩溃,但它有效。我在给定路径中找到该文件。所以,我有点困惑那张纸条的含义。
Google“无法在外部存储上创建自己的应用程序特定目录”是什么意思?