Android-将URL转换为文件
我有这样一个URL:Android-将URL转换为文件,android,android-file,Android,Android File,我有这样一个URL: String url = "https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-ash4/t1/226654_10200335941702035_1975023945_n.jpg" 我想将此url转换为文件,我尝试了以下操作: fileName = new URL(url); sourceFile = new File(fileName.getFile()); 我也试过: sourceFile = new File(fi
String url = "https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-ash4/t1/226654_10200335941702035_1975023945_n.jpg"
我想将此url转换为文件,我尝试了以下操作:
fileName = new URL(url);
sourceFile = new File(fileName.getFile());
我也试过:
sourceFile = new File(fileName.getPath());
但这两种方法都不适用于我。应该做什么?您不能将
文件
用于网络路径。您必须先下载该文件,然后才能从中创建文件。您不能直接复制它
请尝试此代码,它适用于HTTP连接
File f=fileCache.getFile(url);
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
}
f是您的输出文件
您可以使用glide库获取url的位图:
注意:我的代码在kotlin中,如果您遇到任何问题,请告诉我。FileCache FileCache=new FileCache(上下文);把它读完整。。。。我们可以获取上传服务器的文件路径吗?文件路径用于提取要上传到服务器的文件。你已经在这里有文件了,那你为什么还需要文件路径呢??
Glide.with(activity).load(imagePath).asBitmap().into(object :SimpleTarget<Bitmap>(){
override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
val file= GetFileFromBitmap().getFileFromBitmap(resource!!,activity)!!)
}
})
class GetFileFromBitmap
{
fun getFileFromBitmap(bitmap: Bitmap,context: Context) : File?
{
val cache = context.externalCacheDir
val shareFile = File(cache, "myFile.jpg")
Log.d("share file type is", shareFile.absolutePath)
try {
val out = FileOutputStream(shareFile)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
out.flush()
out.close()
return shareFile
} catch (e: Exception) {
}
return null
}
}