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.
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.
The getName() returns the name of the file or the directory. The getPath() returns the abstract pathname in the form of a pathname string.
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()) !=
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With