问题
I am trying to save an image from a web URL in an android application however when I run it, the log cat throws an exception saying its "read only". I don't know whats going on.
Here is my downloader class:
public class ImageDownload {
public static void downloader(String imageURL, String fileName) {
try {
URL url = new URL("http://www.exampleurl.com/" + imageURL);
File file = new File(fileName);
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.d("Downloader", "Error: " + e);
}
}
}
When I run this, this is what I get from the logcat:
DEBUG/Downloader(22112): Error: java.io.FileNotFoundException: /example.gif (Read-only file system)
Any help would be great. Thank you.
回答1:
try saving to /sdcard/example.gif
回答2:
The directory that the new File(fileName);
call defaults to is not writeable. To get the path to the file writing directory for the current context, you use getFilesDir(). So new File(getFilesDir()+fileName);
equates to the usual java behaviour of opening a file in the "current" directory.
来源:https://stackoverflow.com/questions/5315560/read-only-error-when-saving-image-from-url-in-android