【发布时间】:2019-03-21 21:56:25
【问题描述】:
我是 Android Studio 的初学者
我也可以从手机存储创建文件,但我需要的是如何从 SD 卡创建文件。我正在使用虚拟设备或 i9000S。
其实我在用:
Android 果冻豆
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" />
【问题讨论】:
标签: java android database file import