0

我已经写了这个。。

String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {

        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), myFileName);

        if(file.exists()) {
            createDelete.setText("Delete file");
            Toast.makeText(SaveToFile.this, myFileName+" auto-created",Toast.LENGTH_LONG).show();
        }
        else if(!file.exists()) 
            Toast.makeText(SaveToFile.this, myFileName+" auto-creation failed",Toast.LENGTH_LONG).show();
    }

当我运行它时,它使吐司失败。我在目录中找不到文件(无论是模拟器还是我的手机)。

清单中添加了权限,版本为 8。模拟器有 512 MB 外部存储器。

4

3 回答 3

0

如果要创建文件,则必须调用 mkdir

File file = new File(Environment..getExternalStorageDirectory(), myFileName);
// To create the file
file.mkdir();

由于 mkdir 是一个布尔值,你也可以这样做

if (file.mkdir()) {
    Toast.makeText(SaveToFile.this, myFileName+" auto-created",Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(SaveToFile.this, myFileName+" auto-creation failed",Toast.LENGTH_LONG).show();
}

如果您有一些子目录,请使用mkdirs(),它将创建缺少的子目录

http://developer.android.com/reference/java/io/File.html#mkdir%28%29

于 2013-09-02T11:35:24.783 回答
0

尝试这个..

if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    //handle case of no SDCARD present
} else {
    File file = new File(Environment.getExternalStorageDirectory()
         +File.separator
         +"myDirectory" //folder name
         +File.separator
         +"myFile.example"); //file name
    file.mkdirs();
}

在你的清单中..

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2013-09-02T11:33:58.270 回答
-1

这样做

String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Update HEre
        File file = new File(Environment.getExternalStorageDirectory() + "/" + myFileName);

        if(file.exists()) {
            createDelete.setText("Delete file");
            Toast.makeText(SaveToFile.this, myFileName+" auto-created",Toast.LENGTH_LONG).show();
        }else{
            file.createNewFile(); //UPDATE HERE
        }
        else if(!file.exists()) 
            Toast.makeText(SaveToFile.this, myFileName+" auto-creation failed",Toast.LENGTH_LONG).show();
    }
于 2013-09-02T11:19:07.917 回答