【问题标题】:try FileInputStream and FileOutputSteam both throw exception尝试 FileInputStream 和 FileOutputSteam 都抛出异常
【发布时间】:2011-05-22 05:34:22
【问题描述】:
try {
FileOutputStream out = new FileOutputStream("p1");
pictureTaken.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}

        case R.id.open:
        ImageView im = (ImageView) findViewById(R.id.im);
        try {
            FileInputStream in = new FileInputStream("p1");
            BufferedInputStream buf = new BufferedInputStream(in);
            byte[] bitMapA= new byte[buf.available()];
            buf.read(bitMapA);
            Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
            im.setImageBitmap(bM);
            if (in != null) {
            in.close();
            }
            if (buf != null) {
            buf.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;

两者都尝试过,但他们没有通过调试,他们只是抓住了......我在网上找到了大部分这些部分并根据我的需要对其进行了修改,但即便如此,这一切都有意义并且有效在我脑海里。只是不明白为什么会抛出异常。

【问题讨论】:

  • 抛出的异常是什么?

标签: android exception fileinputstream


【解决方案1】:

这听起来像是在 Android 上,从您使用的路径 (p1),您只是想保存到应用程序运行文件夹中的文件。从广义上讲,您不能写入任何目录。你会想做这样的事情:

FileOutputStream out = openFileOutput ("p1", MODE_WORLD_WRITABLE);

在第一个代码块中,然后:

FileInputStream in = openFileInput("p1");

在第二个代码块中。

【讨论】:

  • Femi 是对的,在 Android 中 - 您需要使用 openFileInput/openFileOutput 来获取有效的 Stream 对象。
  • 好的,谢谢,developer.android.com 网站让我感到困惑和误导,他们说这是保存和打开的方式。再次感谢!
  • 等等,我还有一个问题,如果我想将图片和其他一些文件保存到一个公开的文件夹中(连接 USB 时可以看到)怎么办。我还使用输入/输出流吗?此外,您通过压缩保存图片,还有哪些其他写入方式(音频、视频等)。抱歉,我刚接触 Android dev =p。
  • openFileOutputopenFileInput 专门用于应用本地的内容。如果要保存 USB 卡上的文件,则可以使用 FileInputStreamFileOutputStream:查看 stackoverflow.com/questions/3551821/… 以获取写入示例。
  • 我从你告诉我要查看的链接中获得了这个,但我仍然没有看到该文件... File sdCard = Environment.getExternalStorageDirectory();文件目录 = 新文件 (sdCard.getAbsolutePath() + "/myapp/photos"); dir.mkdirs();文件文件 = 新文件(目录,“文件名”);尝试{位图 bImage = BitmapFactory.decodeFile(pictureTaken.getPath()); ByteArrayOutputStream 字节 = 新的 ByteArrayOutputStream(); bImage.compress(Bitmap.CompressFormat.JPEG, 100, 字节);字节 b[] = bytes.toByteArray();文件输出流 f = 新文件输出流(文件); f.写(b); f.close(); } 赶上...
猜你喜欢
  • 2011-11-23
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多