【发布时间】:2010-12-28 03:58:44
【问题描述】:
我已经为此烦恼了一段时间了。以下方法应该是下载一个文件,并将其保存到硬盘上指定的位置。
private static void saveImage(Context context, boolean backgroundUpdate, URL url, File file) {
if (!Tools.checkNetworkState(context, backgroundUpdate))
return;
// Get the image
try {
// Make the file
file.getParentFile().mkdirs();
// Set up the connection
URLConnection uCon = url.openConnection();
InputStream is = uCon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
// Download the data
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
// Write the bits to the file
OutputStream os = new FileOutputStream(file);
os.write(baf.toByteArray());
os.close();
} catch (Exception e) {
// Any exception is probably a newtork faiilure, bail
return;
}
}
另外,如果文件不存在,它应该为该文件创建目录。 (如果那个地方已经有另一个文件,它不应该做任何事情)。但是,由于某种原因,mkdirs() 方法永远不会创建目录。我已经尝试了从显式括号到显式创建父文件类的所有方法,但似乎没有任何效果。我相当确定驱动器是可写的,因为它只是在已经确定之后才被调用,在调试时运行它也是如此。因此该方法失败,因为没有创建父目录。谁能告诉我我的称呼有什么问题吗?
另外,如果有帮助,这里是我调用它的文件的来源:
谢谢
【问题讨论】: