Pages

Thursday, March 26, 2020

Program to download a web page

Program to Download a Web page


Java program to download a given web page using URL Class. 


import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;

public class DownloadWebPageDemo {

    public static void DownloadWebPageDemo(String webpage) {
        try {

            // Creating URL object 
            URL url = new URL(webpage);
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

            // Filename in which downloaded content to be saved  
            BufferedWriter writer = new BufferedWriter(new FileWriter("HomePage.html"));

            // read all line from input stream upto end 
            String line;
            while ((line = br.readLine()) != null) {
                writer.write(line);
            }

            br.close();
            writer.close();
            System.out.println("Webpage Downloaded Successfully.");
            System.out.println("Downloaded file saved as HomePage.html");
        }  
        catch (MalformedURLException MalurlEx) {
            System.out.println("URL Exception raised");
        } catch (IOException ie) {
            System.out.println("IOException raised");
        }
    }

    public static void main(String args[])
            throws IOException {
        String url = "https://cprogrampracticals.blogspot.com";
        DownloadWebPageDemo(url);
    }
}

Output of program

Web page Downloaded Successfully.
Downloaded file saved as HomePage.html

Note: HomePage.html file will be downloaded into the folder where a Source file is stored.

* * * * *






Friday, March 6, 2020

Sum of series 1 + 1/2 + 1/3 + 1/4 + ....N

C Program to print sum of series 1 + 1/2 + 1/3 + 1/4 + ....N for the given value of N.

For example, if N=5, output will be sum of 1 + 1/2 + 1/3 + 1/4 + 1/5, i.e. 2.28 

#include<stdio.h>
int main()
{
  int i, N;
  float sum=0;
  printf("Enter N:");
  scanf("%d", &N);
  if(N<1){
  printf("Enter value of N > 0.");
  exit(1);
  }
  for(i=1; i<=N; i++)
  {
   if(i==1)
   {
  sum=1;
  printf("Series = 1");
   }
   else
   {
     sum = sum + (float)1/i;
     printf(" + 1/%d", i);
   }
  }
  printf("\nSum of the series = %0.2f", sum);
  return 0; 
}

Output of program

Enter N:5
Series = 1 + 1/2 + 1/3 + 1/4 + 1/5
Sum of the series = 2.28



Read more C Programming Series Programs here...

< Back to Home Page >