java - 从 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" />
解决方案
要获取 sdcard 根路径,您应该使用
Environment.getExternalStoragexxx
推荐阅读
- node.js - 在 Mongoosejs 中查询嵌套关系
- php - 注意:未定义的索引:变量
- angular - 如何导航到ionic3中的页面
- devexpress - 使用 EventToCommand、Devexpress 将数据传递给 ViewModel
- java - getActionview 在 android 中使用 Searchview 返回 null
- swift - “'AuthDataResult' 类型的值没有成员 'uid'”错误
- javascript - 如何在离线模式下排队 ajax 请求并在使用离线 .js 连接到互联网时自动执行?
- matlab - matlab中是否有一个名为`taskset()`的函数
- javascript - Chrome 扩展程序不断为图标设置动画
- delphi - delphi如何文章微调器