我正在尝试从服务器下载图像并将其保存在SD卡上,但它失败了
当我在模拟器或其他设备上尝试它时,它正常工作,但我的设备没有。我的设备是galaxy mini gt-s5570
这是我的代码:
public String downloadImage(String imageUrl, String id, String folder) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/FBLogoQuiz/" + folder + "/";
Log.d("path", path);
File FBLogoQuiz = new File(path);
FBLogoQuiz.mkdirs();
FBLogoQuiz.mkdir();
String data = "";
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
// create a File object for the parent directory
File FBLogoQuizDirectory = new File(path, id + ".png");
// have the object build the directory structure, if needed.
FBLogoQuizDirectory.createNewFile();
data = String.valueOf(String.format(path + id + ".png"));
FileOutputStream stream = new FileOutputStream(data);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 85, outstream);
byte[] byteArray = outstream.toByteArray();
stream.write(byteArray);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
的Manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Logcat:
05-24 00:26:10.099: W/System.err(28984): java.io.IOException: No such file or directory
05-24 00:26:10.099: W/System.err(28984): at java.io.File.createNewFileImpl(Native Method)
05-24 00:26:10.109: W/System.err(28984): at java.io.File.createNewFile(File.java:1160)
05-24 00:26:10.109: W/System.err(28984): at com.nileworx.footballlogoquiz.GetUpdatesService.downloadImage(GetUpdatesService.java:229)
05-24 00:26:10.109: W/System.err(28984): at com.nileworx.footballlogoquiz.GetUpdatesService.getUpdates(GetUpdatesService.java:197)
05-24 00:26:10.109: W/System.err(28984): at com.nileworx.footballlogoquiz.GetUpdatesService.onHandleIntent(GetUpdatesService.java:127)
05-24 00:26:10.109: W/System.err(28984): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
05-24 00:26:10.109: W/System.err(28984): at android.os.Handler.dispatchMessage(Handler.java:99)
05-24 00:26:10.109: W/System.err(28984): at android.os.Looper.loop(Looper.java:123)
05-24 00:26:10.109: W/System.err(28984): at android.os.HandlerThread.run(HandlerThread.java:60)
答案 0 :(得分:2)
createNewFile()
在创建文件时不会创建新目录。你需要这样做:
FBLogoQuizDirectory().getParentFile().mkdirs();
在创建文件之前。