我是android开发的新手。 我想在外部SD卡中创建一个文件。我经常搜索并尝试不同的代码。但它是在设备存储中创建的,或者根本不创建。 我得到了我的SD卡路径,它位于/ mnt / extSdCard中。 我甚至尝试了几个代码,但是没有代码不起作用。 这段代码找到了我的SD卡位置:
public static String getExternalSdCardPath() {
String path = null;
File sdCardFile = null;
List<String> sdCardPossiblePath = Arrays.asList("external_sd", "ext_sd", "external", "extSdCard");
for (String sdPath : sdCardPossiblePath) {
File file = new File("/mnt/", sdPath);
if (file.isDirectory() && file.canWrite()) {
path = file.getAbsolutePath();
Log.i("LOG", "path is: " + path);
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
File testWritable = new File(path, "test_" + timeStamp);
if (testWritable.mkdirs()) {
testWritable.delete();
} else {
path = null;
}
}
}
if (path != null) {
sdCardFile = new File(path);
} else {
sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
}
return sdCardFile.getAbsolutePath();
}
路径是我的位置。
答案 0 :(得分:0)
您可以使用context.getApplicationContext().getExternalFilesDirs()
获取可用字符串路径数组,包括您想要的路径。但是,它仅适用于Android 4.4 +。
答案 1 :(得分:0)
如果您没有SD卡,以下是使用代码设置SD卡路径的方法Android将只在INTERNAL STORAGE中存储数据 首先在启动Activity
上声明此变量public static String THE_PATH;
然后在onCreate Bundle中的同一个Activity中调用此方法onAvail()
// Is External Storage Available if so use it and desi the path for DBHelper
public void onAvail() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED) &&
(!state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))){
File removable = ContextCompat.getExternalFilesDirs(this, null)[1];
THE_PATH = String.valueOf(removable);
//System.out.println("EXTERNAL PATH ====> " + THE_PATH);
THE_PATH = THE_PATH + "/Documents/";
//System.out.println("new path ====> "+THE_PATH);
}
}
我希望你有一个DBHelper类,就是那个Class
中发生的事情import static <app name here>.MainActivity.THE_PATH;
// Variable str is set in MainActivity as Public static
// to be accessible in the DBHelper Class
//从MainAvtivity调用
public class DBHelper扩展了SQLiteOpenHelper {
public static final String DB_NAME = THE_PATH +"PassWord";