【发布时间】:2014-01-28 11:27:48
【问题描述】:
我想在我的 sdcard 中创建文件夹,我使用了以下代码:
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() + "");
}
}
}
另外,我已经设置了 sdcard 写入权限:
<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 = new File(Environment.getExternalStorageDirectory(), path);试试这个。
-
仅仅创建一个
File对象实际上并没有对 SD 卡做任何事情。如果要创建目录,则需要在该File对象上调用mkdir()。如果你想创建一个文件,你需要在那个对象上调用createNewFile()。 -
@RajeshCP 我试过了,但结果一样。
-
是的,我使用了 mkdir() 和 mkdirs(),正如您在上面的 Log.d(...) 中看到的那样。
-
你可以检查外部存储的状态,是否可写?