使用Java下载文件时如何获取原始文件名 [英] How to get the original file name when downloading file with java

查看:110
本文介绍了使用Java下载文件时如何获取原始文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Java这样从URL下载文件时如何获取原始文件名

How to get original file name when i download file from URL with java like this

File file = new File( "test" ) ;
FileUtils.copyURLToFile(URL, file)

因为我在创建文件时必须输入一个名称,但是在此阶段我还不知道下载文件的原始名称.

Because when i create file i must put a name but at this stage i don't know yet the original name of downloading file.

推荐答案

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

For me the suggested file name is stored in the header file Content-Disposition:

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

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

I am downloading a file from nexus, so for different servers/applications it might be stored in a different header field but it is easy to find out with some tools like firebug for firefox.

以下几行对我来说很好

URL url = new URL(urlString);
// open the connection
URLConnection con = url.openConnection();
// get and verify the header field
String fieldValue = con.getHeaderField("Content-Disposition");
if (fieldValue == null || ! fieldValue.contains("filename=\"")) {
  // no file name there -> throw exception ...
}
// parse the file name from the header field
String filename = fieldValue.substring(fieldValue.indexOf("filename=\"") + 10, fieldValue.length() - 1);
// create file in systems temporary directory
File download = new File(System.getProperty("java.io.tmpdir"), filename);

// open the stream and download
ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());
FileOutputStream fos = new FileOutputStream(download);
try {
  fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} finally {
  fos.close();
}

这篇关于使用Java下载文件时如何获取原始文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆