首页 > 解决方案 > 从 SD 卡创建文件/数据库

问题描述

我是 Android Studio 的初学者

我也可以从手机存储创建一个文件,但我需要的是如何从 SD 卡创建一个文件。我正在使用虚拟设备或 i9000S

实际上我正在使用:

安卓软糖

API等级:18

安卓版本:4.3

如果我使用它File myFile = new File("/sdcard/sample.txt");,它可以工作。

当我使用它时File myFile = new File("/sdcard1/sample.txt");,它不起作用。它给了我一个错误Error: open failed: ENOENT (No such file or directory).

MainActivity.java:

final String NEW_FOLDER_NAME = "TestFolder";
testPath(new File(Environment.getExternalStorageDirectory(), NEW_FOLDER_NAME));
testPath(new File("/storage/emulated/0/", NEW_FOLDER_NAME));
testPath(new File("/storage/emulated/1/", NEW_FOLDER_NAME));
testPath(new File("/storage/sdcard0/Download/", NEW_FOLDER_NAME));
testPath(new File("/storage/sdcard1", NEW_FOLDER_NAME));
b1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        try {
            String E1 = System.getenv("EXTERNAL_STORAGE");
            File F1 = new File(E1, NEW_FOLDER_NAME);
            String E2 = System.getenv("SECONDARY_STORAGE");
            File F2 = new File(E2, NEW_FOLDER_NAME);
            testPath(new File("/storage/sdcard1", NEW_FOLDER_NAME));
            testPath(F1);
            testPath(F2);

            File myFile = new File("/sdcard1/sample.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =
                    new OutputStreamWriter(fOut);
            myOutWriter.append(e1.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(Main1Activity.this, "Save to" + getFilesDir() + ">" + NEW_FOLDER_NAME, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }
});

private void testPath(File path) {
    String TAG = "Debug.MainActivity.java";
    String FOLDER_CREATION_SUCCESS = " mkdir() success: ";
    boolean success;
    if (path.exists()) {
        // already created
        success = true;
    } else {
        success = path.mkdir();
    }
    Log.d(TAG, path.getAbsolutePath() + FOLDER_CREATION_SUCCESS + success);
    path.delete();
}

编辑:我已经从清单文件中添加:

<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

标签: javaandroiddatabasefileimport

解决方案


要获取 sdcard 根路径,您应该使用

Environment.getExternalStoragexxx

推荐阅读