【问题标题】:checking if a directory is created or not, fails?检查目录是否创建失败?
【发布时间】:2012-04-05 06:09:18
【问题描述】:

我正在尝试创建一个目录,我正在检查它是否创建成功,但在屏幕上显示文本,但没有任何显示。

Java 代码:

public void createDirectory() {
    try {
        String strDirectory = "test";
        boolean success = ( new File(strDirectory)).mkdir();
        if (success) {
            Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created", Toast.LENGTH_SHORT);
        } else {
            Toast.makeText(getApplicationContext(), "error occured", Toast.LENGTH_SHORT);
        }
    } catch (Exception e) {
        Log.e("Error", "Error creating directory");
    }
}

【问题讨论】:

  • 没有出现 Toast 似乎表明它既没有做“if”也没有做“else”......这意味着有一个例外,它正在做 Log.e(...)。能发一下logcat吗?

标签: android file-io toast


【解决方案1】:

.show() 放到Both Toast 的结尾....

Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created", 
Toast.LENGTH_SHORT).show();

【讨论】:

    【解决方案2】:

    您是否在清单中添加了使用权限写入外部存储?

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    我实际上不知道它试图在哪里创建目录,因为您没有限定整个路径。你想做什么?

    如果您尝试在 SD 卡上创建它,请执行此操作,

    File f = new File(Environment.getExternalStorageDirectory(), "myfile.txt");
    

    http://developer.android.com/reference/android/os/Environment.html

    请注意,所有应用都可以读取此文件。

    如果您尝试创建应用专用的文件,请执行此操作,

    OutputStream os = context.openFileOutput("myfile.txt");
    

    http://developer.android.com/reference/android/content/Context.html

    请注意,此方法保留用于小文件,因为它使用在许多设备上受限的内部存储。

    最后,总是打印堆栈跟踪,

    Log.e("mytag", "some message", e);
    

    十分之九,这将直接指出问题所在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2019-07-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多