download a pdf using java
<p>I'm writing a program to download a PDF file from server. I'm using some program given here <a href="https://stackoverflow.com/questions/2302233/download-file-by-passing-url-using-java-code">Download file by passing URL using java code</a>, this solution works fine for the sample URL provided in the first answer, but not for PDF, I'm replacing just the URL. Below is my code.</p>

<pre><code>import java.io.*;
import java.net.*;

public class FileDownloadTest {
    final static int size = 1024;

    public static void fileUrl(String fAddress, String localFileName, String destinationDir) {

        // localFileName = "Hello World";
        OutputStream outStream = null;
        URLConnection uCon = null;

        InputStream is = null;
        try {
            URL url;
            byte[] buf;
            int byteRead, byteWritten = 0;
            url = new URL(fAddress);
            outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));

            uCon = url.openConnection();
            is = uCon.getInputStream();
            buf = new byte[size];
            while ((byteRead = is.read(buf)) != -1) {
                outStream.write(buf, 0, byteRead);
                byteWritten += byteRead;
            }
            System.out.println("Downloaded Successfully.");
            System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void fileDownload(String fAddress, String destinationDir) {
        int slashIndex = fAddress.lastIndexOf('/');
        int periodIndex = fAddress.lastIndexOf('.');

        String fileName = fAddress.substring(slashIndex + 1);

        if (periodIndex &gt;= 1 &amp;&amp; slashIndex &gt;= 0 &amp;&amp; slashIndex &lt; fAddress.length() - 1) {
            fileUrl(fAddress, fileName, destinationDir);
        } else {
            System.err.println("path or file name.");
        }
    }

    public static void main(String[] args) {
        String fAddress = "http://singztechmusings.files.wordpress.com/2011/09/maven_eclipse_and_osgi_working_together.pdf";
        String destinationDir = "D:\\FileDownload";
        fileDownload(fAddress, destinationDir);

    }
}
</code></pre>

<p>Here, This pdf has 73 pages, and in my folder, it is download as a PDF of 1KB, when opened in Acrobat Reader, it says that the file might be corrupted.</p>

<p>I've also tried the code provided here <a href="https://dzone.com/articles/java-how-save-download-file" rel="nofollow noreferrer">https://dzone.com/articles/java-how-save-download-file</a>, but the result is same.</p>

<p>please let me know how can I fix this.</p>

<p>Thanks</p>