Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 371
Hayi Avatar asked Nov 20 '15 18:11

Hayi


People also ask

How to get the fileName of a file in java?

The getName() method is a part of File class. This function returns the Name of the given file object. The function returns a string object which contains the Name of the given file object.

How to get the fileName from file path in java?

The getName() returns the name of the file or the directory. The getPath() returns the abstract pathname in the form of a pathname string.

How to get text file name in java?

Java read file to String using BufferedReader BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); String line = null; String ls = System. getProperty("line. separator"); while ((line = reader. readLine()) !=


Video Answer


1 Answers

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

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

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.

The following lines work fine for me

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();
}
like image 102
Clerenz Avatar answered Nov 14 '22 22:11

Clerenz