0

我正在尝试下载一个名为flower.jpg 的文件

 String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/flower.jpg";

 File f = new File(fileName);
 if(!f.exists())
 {
      f.createNewFile();
 }
 DataOutputStream fos = new DataOutputStream(new FileOutputStream(f));
    fos.write(buffer);
    fos.flush();
    fos.close();

效果很好。

但我想把我的文件放在一个新目录 (images) 中,它还不存在。如果我尝试

 String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images/flower.jpg";

我得到:

 11-06 18:19:01.570: W/System.err(17601): java.io.IOException: No such file or directory
 11-06 18:19:01.580: W/System.err(17601):   at java.io.File.createNewFileImpl(Native Method)
 11-06 18:19:01.580: W/System.err(17601):   at java.io.File.createNewFile(File.java:1115)
4

2 回答 2

1

You need to check whether directory 'images' exists and if not create it.

    if (isMediaMounted()) {

                File cnxDir = new File(
                        Environment.getExternalStorageDirectory()
                                + File.separator + "folderName");
                if (!cnxDir.exists()) {

                    cnxDir.mkdir();

                }}

//

 private boolean isMediaMounted() {
    if (Environment.MEDIA_MOUNTED.equals(Environment
            .getExternalStorageState())) {
        return true;
    } else {
        return false;
    }
}
于 2012-11-06T17:29:42.993 回答
0

您需要先创建一个目录:

String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images";
File dir = new File(dirName);
if(!d.exists())
{
     d.mkdirs();
}

String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images/flower.jpg";

File f = new File(fileName);
if(!f.exists())
{
     f.createNewFile();
}
于 2012-11-06T17:32:10.250 回答