在Android上存储.txt文件

时间:2013-12-12 10:51:27

标签: android

所以我犯了严重错误,将一堆.txt文件存储在Android上的Assets文件夹中,只发现它是只读的,我需要能够写入其中一些,删除其他文件并添加新文件需要的时候。

我知道我可以将其存储在SD卡的内部或外部。 如果我在内部存储它,我在哪里放置所有文件?

在这里外部是一个更好的主意吗?

由于

修改

如果用户可以看到这个问题,那么这不是一个主要问题

1 个答案:

答案 0 :(得分:0)

以下是我用于获取存储目录的示例代码:

/**
 * Check if external storage is built-in or removable.
 *
 * @return True if external storage is removable (like an SD card), false
 *         otherwise.
 */
@TargetApi(9)
public static boolean isExternalStorageRemovable() {
    if (hasGingerbread()) {
        return Environment.isExternalStorageRemovable();
    }
    return true;
}

/**
 * Get the external app cache directory.
 *
 * @param context The context to use
 * @return The external cache dir
 */
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
    if (hasFroyo()) {
        return context.getExternalCacheDir();
    }

    // Before Froyo we need to construct the external cache dir ourselves
    final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
    return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}



/**
 * Get a usable cache directory (external if available, internal otherwise).
 *
 * @param context The context to use
 * @param uniqueName A unique directory name to append to the cache dir
 * @return The cache dir
 */
public static File getDiskCacheDir(Context context, String uniqueName) {
    // Check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
    final String cachePath =
            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                    !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
                            context.getCacheDir().getPath();

    return new File(cachePath + File.separator + uniqueName);
}

你找到了放置文件的途径....

现在要安装它们,你应该在第一次运行时将它们从你的资产复制到该文件夹​​,或者创建它们并根据你的需要填充它们......并且没有其他方法可以运送文件使用您的应用程序,他们可以使用资产,您可以从应用程序创建它们,或从某个服务器下载它们。

Edit1:该文件夹将位于Android / data / your_package_name / cache +您想要的任何内容中......

和用于姜饼和froyo的两个函数:

 public static boolean hasFroyo() {
    // Can use static final constants like FROYO, declared in later versions
    // of the OS since they are inlined at compile time. This is guaranteed behavior.
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}

public static boolean hasGingerbread() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
相关问题