0

我有这个代码:

try {
            URL url = new URL (strURL);
            input = url.openStream();
            byte[] buffer = new byte[1500];
            OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");

我得到这个错误:不要硬编码 /sd card/ 使用 environment.getexternalstoragedirectory().getpath() 代替

 OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");

我已经读过:Android 4.2 - Environment.getExternalStorageDirectory().getPath() 行为

所以问题是当我替换它时最终代码是什么?

4

2 回答 2

6

某些手机​​中的sd文件夹名称不同

在三星手机中,它被命名为 external_sd ,您的代码将失败。

control+shift+o --> 在 eclipse 中添加导入,见这个链接

"/sdcard/" is replace with "Environment.getExternalStorageDirectory().getPath()" in your code

问题是您自己调用了一个名为 Environment.java 的文件,因此 Eclipse 没有让我选择导入 Environment 更改该文件。

于 2013-10-18T06:00:57.343 回答
3

您修改后的代码应如下所示

OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+pos+".png");

您应该小心,因为并非所有设备都有/sdcard/路径。

多年来的设备发生了变化,这可能并不总是包含指向正确外部存储目录的链接。

于 2013-10-18T06:00:21.570 回答