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

How to get the original file name when downloading file with java

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

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

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

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

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

我正在从 nexus 下载一个文件,所以对于不同的 servers/applications,它可能存储在不同的 header 字段中,但使用 firebug 等工具很容易找到对于 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();
}