6

I am trying to write a code in java in which user provide a url link and the program take url link and download a web page as it is and save at particular location..same as save as... option available on webpage.

Please can anybody help me

Thanks in advance

Bhavika Thakkar
  • 101
  • 1
  • 1
  • 2

3 Answers3

9

// Sample URL : http://www.novell.com/coolsolutions/tools/downloads/ntradping.zip

import java.io.*;
import java.net.*;


public class UrlDownload {
    final static int size = 1024;

    public static void fileUrl(String fAddress, String localFileName, String destinationDir) {
        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 >= 1 && slashIndex >= 0 && slashIndex < fAddress.length() - 1) {
            fileUrl(fAddress, fileName, destinationDir);
        } else {
            System.err.println("path or file name.");
        }
    }

    public static void main(String[] args) {
        if (args.length == 2) {
            for (int i = 1; i < args.length; i++) {
                fileDownload(args[i], args[0]);
            }
        } else {
        }
    }
}

It is working fully.

Anew
  • 5,175
  • 1
  • 24
  • 36
Nitul
  • 997
  • 12
  • 35
  • Please che your code, maybe the args in the statement `fileDownload(args[i], args[0]);` should be swapped. – Daniele Jan 24 '17 at 13:56
5

You can use Java URL API to get an input stream on the URL then read the from it and write through output stream on a file.

see read data from url, Write to file

Moro
  • 2,088
  • 6
  • 25
  • 34
1

Have a look at the HtmlParser. It has some features that will help you extract resources from a web page.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194