我无法理解 Context.getFileStreamPath 试图测试文件路径是否存在?
我已经尝试理解 getFileStreamPath 的疯狂了几个小时了。 有人可以解释一下如何测试路径=“shop/crates/fruits”是否存在吗? 为了简化测试,我将路径分成了几段。 我以为我已经拥有了。但是当商店存在但没有板条箱时测试就会中断..奇怪! 或者是吗?
public static Boolean pathExists(String path, Context ctx)
{
Boolean result = false;
String[] pathSegments = path.split("/");
String pathStr = "";
for(int i = 0;i<pathSegments.length;i++ )
{
pathStr += pathSegments[i];
if(!ctx.getFileStreamPath(pathStr).exists())
{
result = false;
break;
}
pathStr += "/";
result = true;
}
return result;
}
I have tried to make sense of the getFileStreamPath madness for some hours now.
Could someone please explain how to test if a path = "shop/crates/fruits" exists?
In an attempt to simplify the test i have broken the path in to segments.
I thought i had it. But the test breaks when shop exists but there is no crates..Weird!
Or is it?
public static Boolean pathExists(String path, Context ctx)
{
Boolean result = false;
String[] pathSegments = path.split("/");
String pathStr = "";
for(int i = 0;i<pathSegments.length;i++ )
{
pathStr += pathSegments[i];
if(!ctx.getFileStreamPath(pathStr).exists())
{
result = false;
break;
}
pathStr += "/";
result = true;
}
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,糟糕的 Android API。
秘诀是使用 context.getFilesDir()。这就是您的文件:
之后,该文件将正常运行。
Yeah, the crappy android APIs.
The secret sauce is to use context.getFilesDir(). That's your file:
After that, the file behaves normally.
首先,getFileStreamPath 返回文件系统上存储使用 openFileOutput(String, int) 创建的文件的绝对路径。
您是否想测试内部或外部存储的路径?如果您想使用外部存储,请使用
getExternalFilesDir()
。如果您想使用像res/raw
这样的内部包嵌入资源,那就是另一个故事了:Android 如何访问我放入 res 文件夹中的原始资源?
但我认为它不会起作用你认为得到的方式 它。
阅读此 http://developer.android.com/guide/topics/数据/数据存储.html
小心。
阅读
使用内部存储
章节。另请参阅:
如何在 Android 内部存储上创建文件?
将文件读/写到内部私有存储
http://www.vogella.de/articles/AndroidFileSystem/article.html
First, the
getFileStreamPath
returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.Are you trying to test the internal or external storage's path? If you want to use external storage use
getExternalFilesDir()
. If you want to use internal package embedded resources likeres/raw
, it's another story:Android how to get access to raw resources that i put in res folder?
But I don't think it will work the way you are presuming to get it.
Read this http://developer.android.com/guide/topics/data/data-storage.html
carefully.
Read
Using the Internal Storage
chapter there.Also see:
How to create a file on Android Internal Storage?
Read/write file to internal private storage
http://www.vogella.de/articles/AndroidFileSystem/article.html