Android - java.io.FileNotFoundException

11

当我将位图图像插入文件目录时,它显示文件未找到异常,并显示为“目录”。

这是我的代码:

            File mFolder = new File(getFilesDir() + "/sample");

            if (!mFolder.exists()) {
                mFolder.mkdir();
            }
             FileOutputStream fos = null;
             try {
                 fos = new FileOutputStream(mFolder);
                 bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);

                 fos.flush();
                 fos.close();
              //   MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
             }catch (FileNotFoundException e) {

                 e.printStackTrace();
             } catch (Exception e) {

                 e.printStackTrace();
             }

日志记录:

07-12 01:08:05.434: W/System.err(8170): java.io.FileNotFoundException: /data/data/com.sample.sam/files/sample(Is a directory)
07-12 01:08:05.434: W/System.err(8170):     at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
07-12 01:08:05.434: W/System.err(8170):     at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:239)
07-12 01:08:05.444: W/System.err(8170):     at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
07-12 01:08:05.444: W/System.err(8170):     at java.io.FileOutputStream.<init>(FileOutputStream.java:77)
4个回答

20

在写入流之前,您必须创建文件。

File mFolder = new File(getFilesDir() + "/sample");
File imgFile = new File(mFolder.getAbsolutePath() + "/someimage.png");
if (!mFolder.exists()) {
    mFolder.mkdir();
}
if (!imgFile.exists()) {
    imgFile.createNewFile();
}
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(imgFile);
    bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);
    fos.flush();
    fos.close();
} catch (IOException e) {
     e.printStackTrace();
}

1
如果你想创建一个文件而不是目录,请使用file.createNewFile()。如果路径不存在,你可能还需要使用mkDirs()

0
您正在尝试以写入模式打开目录本身。这是行不通的。您需要指定目录中的文件,例如:
fos = new FileOutputStream(new File(mFolder, "myfile"));

我添加了代码,但是它显示NullPointerException在这一行:bitmap.compress(Bitmap.CompressFormat.PNG,70, fos); - srinu_stack
那是一个无关的问题。也许“bitmap”为空? - Henry

-1
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + "/text/");
dir.mkdir();
File file = new File(dir, "sample.txt");
FileOutputStream os = null;
try {
    os = new FileOutputStream(file);
    os.write(enterText.getText().toString().getBytes());
    os.close();
}
catch (IOException e) {
    e.printStackTrace();
}

请始终将您的回答放在上下文中,而不仅仅是粘贴代码。有关更多详细信息,请参见此处:https://stackoverflow.com/help/how-to-answer。 - gehbiszumeis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接