Android 下载文件获取对应链接文件的名称及扩展名

Android开发文件下载有时候下载文件的时候需要获取文件的名称及扩展名,但是下载链接不包含文件的扩展名及文件名,需要其他的方案解决,下面就有两个解决的方案。

一、通过HttpURLConnection的提供的方法

public static String guessContentTypeFromStream(InputStream in);

BufferedInputStream  bis = null;
HttpURLConnection  connection = null;
URL  url = new URL(strUrl);
connection = (HttpURLConnection)url.openConnection();
connection.connect();
bis = new BufferedInputStream(connection.getInputStream());
System.out.println("filetype:"+HttpURLConnection.guessContentTypeFromStream(bis));

二、获取connection.getHeaderField("Content-Disposition");

    HttpURLConnection connection = null;  
       
    connection = (HttpURLConnection) new URL(url)
  connection .openConnection();  
  connection.setRequestMethod("GET");  
  connection.connect();     
  int code = 0;  
  code = connection.getResponseCode();   
if (code == HttpURLConnection.HTTP_OK) { 
String fileName = connection.getHeaderField("Content-Disposition"); 
// 通过Content-Disposition获取文件名 
if (fileName == null || fileName.length() < 1) { 
   // 通过截取URL来获取文件名 
  URL downloadUrl = connection.getURL(); 
  // 获得实际下载文件的URL 
  fileName = downloadUrl.getFile(); 
  fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
  } else {
  fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=") + 9), "UTF-8");
  // 存在文件名会被包含在""里面,所以要去掉,否则读取异常 
  fileName = fileName.replaceAll("\"", "");
  }
 } 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值