Android:创建的文件不会转到SD卡

时间:2016-05-29 08:30:43

标签: android file save

我正在搜索如何在SD卡中创建文件。目前我有这段代码:

public class Store {

private final String fileName = "histoires.json";

public void createFile(Context context, String json) {
    File file = new File (getDir(context), fileName);
    try {
        FileOutputStream out = new FileOutputStream(file);
        out.write(json.getBytes());
        out.flush();
        out.close();

    } catch (Exception e) {
        Log.e("Erreur enregistrement du fichier", e.toString());
    }
}

private File getDir(Context context) {
    File dir;
    if(!isExternalStorageReadable() || !isExternalStorageWritable()) {
        dir = context.getFilesDir();
    }
    else {
        dir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
    }
    return dir;
}

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}}

在我的活动中,我只是称之为:

new Store().createFile(this, json);

问题是:我看到了我的文件但总是在手机内存中。我使用了getExternalFilesDir()。无论如何,它不想将我的文件保存在SD卡中。 我在return语句中检查了getDir()中我的dir变量的内容,它是: /storage/emulated/0/Android/data/com.histoire_horreur/files/Documents

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

尝试使用:

String mfileName;
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();