我想在我的SD卡文件夹中创建文件夹,我用下面的代码:如何在SD卡中的Android
public class Screen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
operateOnFirstUsage();
}
private void operateOnFirstUsage() {
String state = Environment.getExternalStorageState();
Log.d("Media State", state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
File appDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/");
Log.d("appDirectroyExist", appDirectory.exists() + "");
if (!appDirectory.exists())
Log.d("appDir created: ", appDirectory.mkdir() + "");
File dbDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Database/");
Log.d("dbDirectroyExist", dbDirectory.exists() + "");
if (!dbDirectory.exists())
Log.d("dbDir created: ", dbDirectory.mkdirs() + "");
File themesDirectory = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/Themes/");
Log.d("themesDirectroyExist", themesDirectory.exists() + "");
if (!themesDirectory.exists())
Log.d("themesDir created: ", themesDirectory.mkdirs() + "");
}
}
}
而且,我已经设置了SD卡写入权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我已经运行的应用程序几次,每次我得到的logcat输出:
01-09 21:38:13.701: D/Media State(15363): mounted
01-09 21:38:13.701: D/appDirectroyExist(15363): false
01-09 21:38:13.701: D/appDir created:(15363): false
01-09 21:38:13.701: D/dbDirectroyExist(15363): false
01-09 21:38:13.701: D/dbDir created:(15363): false
01-09 21:38:13.701: D/themesDirectroyExist(15363): false
01-09 21:38:13.701: D/themesDir created:(15363): false
我看过类似的问题,但没有使用得到。我该怎么做才能让代码运行?我的问题是什么?
File file = new File(Environment.getExternalStorageDirectory(),path);尝试这个。 – Triode
只是创建一个'File'对象实际上并没有对SD卡做任何事情。如果你想创建一个目录,你需要在'File'对象上调用'mkdir()'。如果你想创建一个文件,你需要在该对象上调用'createNewFile()'。 –
@RajeshCP我试过了,但结果相同。 –