你有一个长度为 0 的文件,因为你只是用 url.getFile() 的结果名称创建它,url.getFile() 返回一个与获取的文件名对应的字符串。所以你最终得到一个名为图片的文件:
https://graph.facebook.com/v4.0/10211842143528384/picture?height=200&width=200&migration_overrides=%7Boctober_2012%3Atrue%7
但是内容呢?您必须将它们作为流从 Internet 下载并将该流馈送到文件中。使用纯 Java 有很多方法可以做到这一点。来自https://www.baeldung.com/java-download-file的基本复制粘贴
try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream());
FileOutputStream fileOutputStream new FileOutputStream(FILE_NAME)) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
} catch (IOException e) {
// handle exception
}
由于您使用的是 android,我强烈建议您使用功能齐全的网络库,例如 OkHttp3、Retrofit 或 Volley,但我认为您会更好地学习 Java 基础知识,然后跳转到上述库。
请记住,对于 android,您需要 INTERNET 权限才能访问互联网,然后如果您下载到外部存储上的文件,您还需要 EXTERNAL_STORAGE 权限。安卓代码片段:
try {
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// Read from the Network stream
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/downloaded.png");
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
// Feed the bytes read from the input stream into our output stream
output.write(data, 0, count);
}
// Flushing the out stream.
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
这个 sn-p 做网络工作,所以你需要在后台线程上运行它。希望我的回答对您有所帮助,如果没有,请告诉我我还能为您做些什么。