作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我开发了一个应用程序- 下载一些数据(.png 和.wav 文件)- 插入每个文件下载到数据库的路径(SQLite)
到目前为止一切顺利,一切正常。一些用户问我有没有办法将下载的数据移动到 sd 卡中以节省一些内部空间。
现在我用这行代码创建目录
File directory = getApplicationContext().getDir("folderName", Context.MODE_PRIVATE);
然后应用程序将用我下载的所有内容填充它。
我尝试使用这段代码:
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
System.out.println("Path: " + file.getPath());
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
这将创建一个文件夹和一个文本文件到:/storage/emulated/0/TestFolder/MyTest.txt哪个不是我的sdcard目录,应该是:/storage/sdcard1/TestFolder/MyTest.txt
所以我的问题是:- 我在 SD 卡中将应用程序的私有(private)数据(.png 和 .wav 文件)保存在何处以及如何保存?
最佳答案
getExternalFilesDir
、getExternalStorageDirectory
或亲戚并不总是返回 SD 卡上的文件夹。例如,在我的三星上,它会返回一个模拟的内部 SD 卡。
您可以使用 ContextCompat.getExternalFilesDirs
获取所有外部存储设备(包括可移动设备) .
我的下一步是使用设备上可用空间最大的文件夹。为此,我枚举了 getExternalFilesDirs
,并对每个文件夹调用了 getUsableSpace
。
我使用此代码将位图存储(缓存)在设备上名为“bmp”的文件夹中。
@SuppressWarnings("ResultOfMethodCallIgnored")
private static File[] allCacheFolders(Context context) {
File local = context.getCacheDir();
File[] extern = ContextCompat.getExternalCacheDirs(context);
List<File> result = new ArrayList<>(extern.length + 1);
File localFile = new File(local, "bmp");
localFile.mkdirs();
result.add(localFile);
for (File anExtern : extern) {
if (anExtern == null) {
continue;
}
try {
File externFile = new File(anExtern, "bmp");
externFile.mkdirs();
result.add(externFile);
} catch (Exception e) {
e.printStackTrace();
// Probably read-only device, not good for cache -> ignore
}
}
return result.toArray(new File[result.size()]);
}
private static File _cachedCacheFolderWithMaxFreeSpace;
private static File getCacheFolderWithMaxFreeSpace(Context context) {
if (_cachedCacheFolderWithMaxFreeSpace != null) {
return _cachedCacheFolderWithMaxFreeSpace;
}
File result = null;
long free = 0;
for (File folder : allCacheFolders(context)) {
if (!folder.canWrite()) {
continue;
}
long currentFree = folder.getUsableSpace();
if (currentFree < free) {
continue;
}
free = currentFree;
result = folder;
}
_cachedCacheFolderWithMaxFreeSpace = result;
return result;
}
关于Android 将下载的数据保存到 SD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34610741/
我是一名优秀的程序员,十分优秀!