I tried your routine. Works fine for me.

I used the URL

"http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3"

and got a playable MP3 file of exactly 1,430,174 bytes.

Next I tried JPEG:

"http://weknowyourdreams.com/images/beautiful/beautiful-01.jpg"

works fine.

I suspect what happened is that you used URL of a web page instead of the audio/video/pic file by mistake. For example, if you used the URL

"http://weknowyourdreams.com/image.php?pic=/images/beautiful/beautiful-01.jpg"

instead of the one above, you will not get a proper JPG. You'll have to use "View Image" or "Copy Image Location" in your browser.

Answer from Oleksiy Grechnyev on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java io › download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - OutputStream os = new FileOutputStream(FILE_NAME, true); After we’ve made this change, the rest of the code is identical to the one from Section 2. We’ve seen in this article several ways to download a file from a URL in Java.
🌐
Medium
pkslow.medium.com › multiple-ways-to-download-files-from-internet-in-java-ced5d3aaae2c
Multiple Ways to Download Files from Internet in Java | by Larry Deng | Medium
April 3, 2023 - private static void javaNIO1() { try { URL website = new URL(URL); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("pkslow.nio.html"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } catch (Exception e) { throw new RuntimeException(e); } } ... private static void javaNIO2() { try { URL website = new URL(URL); try (InputStream in = website.openStream()) { Files.copy(in, Paths.get("pkslow.nio2.html"), StandardCopyOption.REPLACE_EXISTING); } } catch (Exception e) { throw new RuntimeException(e); } }
🌐
amitph
amitph.com › home › java › how to download a file from url in java
How to Download a File from URL in Java - amitph
November 22, 2024 - URL url = new URL("https://www.google.com"); try ( ReadableByteChannel inputChannel = Channels.newChannel(url.openStream()); FileOutputStream fileOutputStream = new FileOutputStream(outputPath); FileChannel outputChannel = fileOutputStream.getChannel(); ) { outputChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE); }Code language: Java (java) We can also use HttpClient provided by the Java NET package. Next, is an example of using HttpClient to download a file and save it on the disk.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-download-file-url
Java Download File from URL | DigitalOcean
August 4, 2022 - It shows both ways to download file from URL in java. JavaDownloadFileFromURL.java · package com.journaldev.files; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class JavaDownloadFileFromURL { public static void main(String[] args) { String url = "https://www.journaldev.com/sitemap.xml"; try { downloadUsingNIO(url, "/Users/pankaj/sitemap.xml"); downloadUsingStream(url, "/Users/pankaj/sitemap_stream.xml"); } catch (IOException e) { e.pr
🌐
Stack Abuse
stackabuse.com › how-to-download-a-file-from-a-url-in-java
How to Download a File from a URL in Java
August 21, 2018 - String fileName = "D:\\Demo\file.txt"; FileOutputStream fos = new FileOutputStream(filename); Int byte; while((byte = inputStream.read()) != -1) { fos.write(byte); } The last thing required to be done is closing all the open resources in order to ensure that the system resources are not overutilized and that there are no memory leaks. So there you have it - these are the simplest ways to download a file using the basic Java code and other third party libraries.
🌐
codippa
codippa.com › home › download file from url in java
Java - Download file from a URL in 3 ways
January 12, 2025 - Java code to download file from URL with this method is given below. import java.net.URL; import java.net.URLConnection; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileDownloader { public static void main(String[] args) { OutputStream os = null; InputStream is = null; String fileUrl = "http://200.34.21.23:8080/app/file.txt"; String outputPath = "E:\\downloads\\downloaded.txt"; try { // create a url object URL url = new URL(fileUrl); // connection to the file URLConnection connection = url.openConnection();
Top answer
1 of 3
1

None of your code attempts to convert to characters; you're passing bytes through unchanged, so there is no need to worry about encoding. Your code will work fine.

It's only when you use Readers and Writers that you have to worry about encoding.

2 of 3
1

Assuming that con is an instance of URLConnection, its getInputStream() will provide you a direct network stream reading the bytes as sent by the server. No conversion will be made. Since you are transferring the bytes directly to the file, they are stored in the files without any modification.

Assuming that the server sent the files using the UTF-8 encoding and that the tool you use to open the file afterwards uses the UTF-8 encoding as well, you will see all characters correctly. The same applies to any other encoding, as long as the server and the tool use the same encoding. Your program does not add anything to it as it simply transfers bytes, not characters.

By the way, such a transfer can be made much simpler using recent APIs:

try(ReadableByteChannel in=Channels.newChannel(con.getInputStream());
    FileChannel out=FileChannel.open(Paths.get("C:\\programs\\TRYFILE.csv"),
        StandardOpenOption.CREATE, StandardOpenOption.WRITE,
        StandardOpenOption.TRUNCATE_EXISTING)) {
    out.transferFrom(in, 0, Long.MAX_VALUE);
}

It gets even more readable when you use import static java.nio.file.StandardOpenOption.*;:

try(ReadableByteChannel in=Channels.newChannel(con.getInputStream());
    FileChannel out=FileChannel.open(Paths.get("C:\\programs\\TRYFILE.csv"),
                                     CREATE, WRITE, TRUNCATE_EXISTING) {
    out.transferFrom(in, 0, Long.MAX_VALUE);
}
Find elsewhere
🌐
javaspring
javaspring.net › blog › java-file-download
Java File Download: A Comprehensive Guide — javaspring.net
FileOutputStream is used to write data to the destination file (destinationFile.txt). A buffer of size 1024 bytes is used to read and write data in chunks, which is more efficient than reading and writing one byte at a time.
🌐
STechies
stechies.com › download-file-from-url-java
How to Download a File from a URL in Java
Now, if we take the byte-by-byte data from an input stream & write the bytes to a file output stream, we can achieve downloading using URL. ... import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.net.URL; class Main{ public static void URLDnldFile(URL urlink, String fileName) throws IOException{ try (InputStream inp = urlink.openStream(); BufferedInputStream bis = new BufferedInputStream(inp); FileOutputStream fops = new FileOutputStream(fileName)){ byte[] d = new byte[1024]; int i; while ((i = bis.read(d, 0, 1024)) != -1){ fops.write(d, 0, i); }}} public static void main(String[] args) throws Exception{ System.out.println("Call this method when you want your application to have this."); //Call the URLDnldFile() method }}
🌐
Matjazcerkvenik
matjazcerkvenik.si › developer › java-download-file-via-http.php
Java Download File via HTTP - Matjaž Cerkvenik
FileChannel in Java will retrieve data from cache and if the file in cache is not complete, also Java cannot download complete file. This looks like the sever stops sending data, because no more data will be received. // url=http://www.example.com/testFile.zip // localFile=/path/to/testFile.zip public void download(String url, String localFile) throws Exception { System.out.println("Downloading " + localFile); ReadableByteChannel in = Channels.newChannel(new URL(url).openStream()); FileOutputStream fos = new FileOutputStream(localFile); FileChannel channel = fos.getChannel(); channel.transferFrom(in, 0, Long.MAX_VALUE); channel.close(); fos.close(); System.out.println("Download complete"); }
🌐
Stack Overflow
stackoverflow.com › questions › 54575788 › download-pdf-file-from-outputstream
java - Download PDF file from Outputstream - Stack Overflow
July 2, 2019 - @Override public void constructDocumentById(SisDocuments document) { try { File inputFile = new File("input.txt"); File xsltfile = new File(path + "dz/sis-fop.xsl"); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStream out; out = new java.io.FileOutputStream("employee.pdf"); try { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); TransformerFactory factory = TransformerFactory.newInstance(); Source xslt = new StreamSource(xsltfile); Transformer transfo
🌐
Coderanch
coderanch.com › t › 366350 › java › download-file-OutputStream-Servlets
download file using OutputStream from Servlets (Servlets forum at Coderanch)
September 25, 2008 - Download a file from a web app using a Servlet and then save the file with its original name and extension, currently Im using ServletOutStream to write data to the response. Here is the code I use in Servlet:.
🌐
CodeJava
codejava.net › java-se › networking › use-httpurlconnection-to-download-file-from-an-http-url
Java HttpURLConnection to download file from an HTTP URL
July 18, 2019 - package net.codejava.networking; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * A utility that downloads a file from a URL.
🌐
Mkyong
mkyong.com › home › java › java – how to download a file from the internet
Java - How to download a file from the Internet - Mkyong.com
March 16, 2017 - package com.mkyong; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class HttpUtils { public static void main(String[] args) { String fromFile = "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest"; String toFile = "F:\\arin.txt"; try { URL website = new URL(fromFile); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(toFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } catch (IOException e) { e.printStackTrace(); } } } Commons IO · FileChannel JavaDoc ·
🌐
Oracle
docs.oracle.com › javase › 6 › docs › api › java › io › FileOutputStream.html
FileOutputStream (Java Platform SE 6)
java.lang.Object java.io.OutputStream java.io.FileOutputStream ... A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file ...
🌐
Mkyong
mkyong.com › home › java › how to download file from website- java / jsp
How to download file from website- Java / Jsp - Mkyong.com
April 15, 2010 - OutputStream output = new FileOutputStream( file ); while ( (n = input.read(buffer)) != -1) { if (n > 0) { output.write(buffer, 0, n); } } But the file is saved as encoded. Can you please suggest any thing else? Its a zip file ... i am getting junk data along with csv while downloading from screen.the junk data is source page of jsp