gpt4 book ai didi

Android 将下载的数据保存到 SD

转载 作者:行者123 更新时间:2023-11-29 20:12:02 25 4
gpt4 key购买 nike

我开发了一个应用程序- 下载一些数据(.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 文件)保存在何处以及如何保存?

最佳答案

getExternalFilesDirgetExternalStorageDirectory 或亲戚并不总是返回 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com