栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Java下载文件时如何获取原始文件名

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Java下载文件时如何获取原始文件名

对我来说,建议的文件名存储在头文件Content-Disposition中:

Content-Disposition: attachment; filename="suggestion.zip"

我正在从nexus下载文件,因此对于不同的服务器/应用程序,它可能存储在不同的标头字段中,但是很容易通过诸如firebug的firebug之类的工具来查找。

以下几行对我来说很好

URL url = new URL(urlString);// open the connectionURLConnection con = url.openConnection();// get and verify the header fieldString fieldValue = con.getHeaderField("Content-Disposition");if (fieldValue == null || ! fieldValue.contains("filename="")) {  // no file name there -> throw exception ...}// parse the file name from the header fieldString filename = fieldValue.substring(fieldValue.indexOf("filename="") + 10, fieldValue.length() - 1);// create file in systems temporary directoryFile download = new File(System.getProperty("java.io.tmpdir"), filename);// open the stream and downloadReadableByteChannel rbc = Channels.newChannel(con.getInputStream());FileOutputStream fos = new FileOutputStream(download);try {  fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);} finally {  fos.close();}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417413.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号