Java Program to Download Image From an URL

In this program we will see how we can download image from an URL in java language.

Java Program to Download Image From an URL

For that we will be using this image at the URL

Java Program to Download Image from URL

Image Source: https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg

Explanation:

To download an image from the internet we first need the URL of the image. After that we need to read the image from the site and then write it into our system storage.

Method-1: Java Program to Download Image From an URL By Using Input and OutputStream

Approach:

  • Use a try catch block to catch any IO errors caused .
  • Store the URL of the image in an URL object and store the path to save the file in a string.
  • Create an InputStream object on the URL provided to fetch the image by using openStream() method and an OutputStream object on the download path to store the object.
  • Use a while loop till the EOF to copy the image from the InputStream object to the FileOutputStream object.
  • Close the stream objects and print the path of the image on successful download.

Program:

package btechgeeks;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class Main
{  
    public static void main(String[] args)
    {
        //Try catch block to catch any IO error thrown
        try
        {
            //URL of the image
            URL link = new URL ("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg");
            //The path to store the downloaded image into
            String downloadPath = "D:\\ImageProgram/downloadedImage.jpg";
            //Using inputStream to read the image from the URL
            InputStream is = link.openStream();
       
            //Saving the image into the path specified
            OutputStream fos = new FileOutputStream(downloadPath);
            int ch;
            //Loop until all the data from the image is copied and we reach the EOF
            while ((ch = is.read()) != -1) 
            {
                    fos.write(ch);
            }
            //Output statement to execute upon successful download
            System.out.println("Your image has been downloaded successfully and is stored at " +downloadPath);
            //Close the objects.
            is.close();
            fos.close();
        }
        //Catch block to catch IO errors
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Output:

Your image has been downloaded successfully and is stored at D:\ImageProgram/downloadedImage.jpg

In File Explorer-

Java Program to Download Image From URL

Method-2: Java Program to Download Image From an URL By Using ImageIO

Syntax:

ImageIo.write(imageObj,extension,image,FileObject )

Where,

  • imageObj – Image object is the object we have stored the fetched image in
  • Extension – Extension is the extension of the file i.e. jpg, jpeg, png etc
  • FileObject- It is the file we are storing the file in.

Approach:

  • Create an object of BufferedImage.
  • Inside a try catch block, store the image url in an URL object.
  • Fetch the image from the url using ImageIO.read( ) method.
  • Write to the file using ImageIo.write( ) method.

Program:

package btechgeeks;

import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;

public class Main
{
    public static void main(String[] args)
    {
        // Create an BufferedImage object to store the image
        BufferedImage img = null;
        // Try catch block to catch any IO error thrown
        try
        {
            // Image Link
            URL link = new URL("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg");

            // Read image from the link
            img = ImageIO.read(link);

            // Write the image to the folder
            ImageIO.write(img, "jpg",new File("D:\\ImageProgram/downloadedImage.jpg"));

            System.out.println("Your image has been downloaded successfully");
        }
        // Catch block to catch IO erroes
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Output:

Your image has been downloaded successfully

In File Explorer-

Java Program to Download Image From URL

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Menu Driven Banking Application

In this article we are going to see a menu driven banking application by using Java programming language.

Java Menu Driven Banking Application

We will write a program for basic banking applications which mostly involve in

  1. Opening Account
  2. Depositing Money
  3. Withdrawing Money
  4. Account Statement

For the below menu driven program, we have used below user defined method.

  • openAcc( ) – Asks the user for details and creates the account
  • accInfo( ) – Displays the user name, account type and account number
  • balanceInq( ) – Displays the balance available
  • withdraw( ) – Withdraw amount from the user account if possible.
  • deposit( ) – Deposit amount into the bank account

Approach:

  • Inside a while loop display all the functionalities.
  • Ask the user to enter their choice.
  • Use switch case for navigation.
  • Upon account creation ask the user to enter their user name, account type, account number and balance. Store them all in static variables.
  • Now to display the user info display the user name, account number and account type to the console.
  • Now to see the the account balance, print out the available balance to the console.
  • If the user want to deposit into their account, ask the user for deposit amount then add the value to the current balance and display the new balance.
  • If the user wants to withdraw from the account, ask the user for withdraw amount then check if the entered amount is not greater than the balance then print the new balance after subtracting the amount, else print insufficient balance.

Program:

import java.util.*;
import java.lang.*;

public class Main
{
    static String username= null;
    static String acctNo= null;
    static String accType= null;
    static long balance = 0;

        // Driver method
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int ch=1;
        // Loop to select the choices
        while(ch!=0)
        {
            // Menu
            System.out.println("---\t Services Available \t---");
            System.out.println("1. Open a new account");
            System.out.println("2. Show account information");
            System.out.println("3. Balance inquiry");
            System.out.println("4. Withdraw money");
            System.out.println("5. Deposit money");
            System.out.println("6. Exit");
            System.out.println("Enter your choice number");
            ch = sc.nextInt();
           
            // Switch case to use the menu
            switch(ch)
            {
                case 1: openAcc();
                        System.out.println("\n");
                        break;
                case 2: accInfo();
                        System.out.println("\n");
                        break;
                case 3: balanceEnq();
                        System.out.println("\n");
                        break;
                case 4: withdraw();
                        System.out.println("\n");
                        break;
                case 5: deposit();
                        System.out.println("\n");
                        break;
                case 6: System.out.println("Thank you!!");
                        System.exit(0);
                        break;
                default: System.out.println("Wrong Input!!! Retry");
            }
        }
    }
    
    // To open an account
    static void openAcc()
    {
        //Ask the user to enter his name
        System.out.println("Enter your name: ");
        Scanner sc = new Scanner(System.in);
        username = sc.nextLine();
        //Ask the user to enter his account number (generally Bank provides AC no.)
        System.out.println("Enter your account number: ");
        acctNo = sc.nextLine();
        //Ask the user to enter his Account type
        System.out.println("Enter the account type you want to create: ");
        accType = sc.nextLine();
        //Ask the user to enter his opening account balance
        System.out.println("Enter your opening account balance: ");
        balance = sc.nextInt();
        
        System.out.println("Welcome "+username);
        System.out.println("Your account has been successfully created.");
    }
   
    // To view the account number and other information
    static void accInfo()
    {
        System.out.println("Welcome "+username);
        System.out.println("Your account number is "+acctNo+" and is a "+accType+" account");
    }

    // To view the balance
    static void balanceEnq(){
        System.out.println("Your current account balance is: "+balance);
    }

    // To withdraw from the account
    static void withdraw(){
        System.out.println("Enter amount to withdraw from your account: ");
        Scanner sc = new Scanner(System.in);
        long amount = sc.nextLong();
        //If your withdraw amount is more than your available balance
        //then you can not withdraw due to insufficient fund
        if(amount>balance)
            System.out.println("Insufficient Funds!!!");
        else
        {
            //deducting from available balance
            balance -= amount;
            System.out.println("The amount of "+amount+" has been successfully debited.");
            System.out.println("Your new balance is: "+balance);
        }
    }

    // To deposit money to the account
    static void deposit(){
        System.out.println("Enter amount to deposit in your account: ");
        Scanner sc = new Scanner(System.in);
        long amount = sc.nextLong();
        //adding to available balance
        balance += amount;
        System.out.println("The amount of "+amount+" has been successfully credited.");
        System.out.println("Your new balance is: "+balance);
    }
}

Output:

--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
2
Welcome null
Your account number is null and is a null account


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
1
Enter your name: 
Shankar
Enter your account number: 
227755449933
Enter the account type you want to create: 
Saving
Enter your opening account balance: 
5000
Welcome Shankar
Your account has been successfully created.


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
3
Your current account balance is: 5000


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
2
Welcome Shankar
Your account number is 227755449933 and is a Saving account


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
5
Enter amount to deposit in your account: 
6000
The amount of 6000 has been successfully credited.
Your new balance is: 11000


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
3
Your current account balance is: 11000


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
4
Enter amount to withdraw from your account: 
5500
The amount of 5500 has been successfully debited.
Your new balance is: 5500


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
5
Enter amount to deposit in your account: 
2500
The amount of 2500 has been successfully credited.
Your new balance is: 8000


--- Services Available ---
1. Open a new account
2. Show account information
3. Balance inquiry
4. Withdraw money
5. Deposit money
6. Exit
Enter your choice number
6
Thank you!!

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Area of triangle java – Java Program to Find Area of Triangle

Area of triangle java: In the previous article we have discussed Java Program to Find Volume of Prism

In this article we will discuss how to find the area of a triangle in different ways.

Program to Find Area of Triangle

Before jumping into the program directly, first let’s see how to find the area of a triangle.

Area formula of triangle: (width*height)/2

Example:

Example-1

When the width of the triangle = 20.0 
and the height of the triangle = 110.5
Then area of the triangle  => (width*height)/2 
                                          => (20.0*110.0)/2 
                                          = 1105.0
Example-2

When the width of the triangle = 3
and the height of the triangle = 4
Then area of the triangle => (width*height)/2 
                                         => (3*4)/2
                                         = 6

Let’s see different ways to find find area of triangle:

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Method-1 : Java Program to Find Area of Triangle Using Static Value

In this the values of width and height are static values, means the values are already defined in the program. So, let’s see the program to understand it more clearly.

import java.util.*;

class Main
{
   public static void main(String args[])
   {   // width of triangle
      double width = 20.0;
      // hight of triangle
      double height = 100.5;
      //finding area
      double area = (width * height)/2;
      // printing the area
      System.out.println("Area of Triangle: " + area);      
    }
}
Output:
Area of Triangle: 1005.0

Method-2 : Java Program to Find Area of Triangle Using User Defined Value

In this the values of width and height are dynamic values, means it will ask the user for the input values in the program. So, let’s see the program to understand it more clearly.

import java.util.*;

class Main
{
   public static void main(String args[]) 
    {   
       
       Scanner sc= new Scanner(System.in);
        
        System.out.println("Enter the width of triangle:");
        double width= sc.nextDouble();
 
        System.out.println("Enter the height of triangle:");
        double hight= sc.nextDouble();
 
       //Area = (width*height)/2
       double area=(width*hight)/2;
       System.out.println("Area of triangle: " + area);      
   }
}
Output:

Enter the width of triangle: 2
Enter the height of triangle: 4
Area of triangle: 4.0

Method-3: Java Program to Find Area of Triangle Using Constructor

In this the width and height values will be taken by the user and those values will be passed as parameter to the constructor where the actual area finding logic is present.

So, let’s see the program to understand it more clearly.

import java.util.*;


class TriangleArea
{
      long area;
      // Constructor
      TriangleArea(long width,long hight)
    {
      //finding area
      area=(width*hight)/2;  
    }
}
 
//Driver Class
class Main
{
   public static void main(String args[]) 
    {   
      Scanner sc= new Scanner(System.in);
      // Asking user to take width input
      System.out.println("Enter the width of triangle:");
      long width= sc.nextLong();
      // Asking user to take hight input
      System.out.println("Enter the height of triangle:");
      long hight= sc.nextLong();
      TriangleArea t=new TriangleArea(width,hight);
      System.out.println("Area of triangle: " + t.area);      
   }
}
Output:

Enter the width of triangle: 4
Enter the height of triangle: 4
Area of triangle: 8

Method-4: Java Program to Find Area of Triangle Using User Defined Method

In this the width and height values will be taken by the user and those values will be passed as parameter to a user defined method where the actual area finding logic is present.

So, let’s see the program to understand it more clearly.

import java.util.*;
 
//Driver Class
class Main
{
   public static void main(String args[]) 
    {   
      Scanner sc= new Scanner(System.in);
      // Asking user to take width input
      System.out.println("Enter the width of triangle:");
      long width= sc.nextLong();
      System.out.println("Enter the height of triangle:");
      long hight= sc.nextLong();
      //calling the method
      TriangleArea(width,hight);
    }
     
     //user defined method  
    public static void TriangleArea(long width,long hight)
    {
      long area=(width*hight)/2;  
      System.out.println("Area of triangle: " + area); 
    }
    
}
Output:

Enter the width of triangle: 4
Enter the height of triangle: 4
Area of Triangle: 8

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Related Java Programs:

Java Program to Delete a File

Java Program to Delete a File

In this article we are going see how to delete a file by using Java programming language.

Java Program to Delete a File

JavaIO is a package that contains methods to do input and output operations. It helps us with file handling in java.

Java NIO package is also another package that handle IO operations and it might seem a replacement to JavaIO but it is not. Both these packages are used separately.

Let’s see the program to understand it clearly.

Method-1: Java Program to Delete a File By Using  java.io.File.delete()

Methods Used:

  • delete( ) – It is a Boolean method that  deletes the file and then returns 1 if file is successfully deleted else returns 0.

Approach:

  • Store the file path in a file object.
  • Delete the file using Boolean method delete( ) in java.
  • If file was deleted print “file has been deleted”, else print “Unable to delete file”.

Program:

import java.io.*;

public class Main
{
    public static void main(String[] args)
    {
        //object of File class created
        File fi = new File("New Folder/file.docx");
        //Tries to delete the file using java.io delete() function
            if(fi.delete())
            {
                System.out.println("File has been deleted");
            }
            //Executes if file fails to delete
            else
            {
                System.out.println("Unable to delete file");
            }
    }
}

Output:

File has been deleted

Method-2: Java Program to Delete a File By Using java.nio.file.files.deleteifexists()

Methods Used:

  • deleteIfExists(path) – It takes the path as parameter and then deletes the file.

Approach:

  • We will do it by using a try catch block.
  • In the try section use the deleteIfExists( ) function with the file path as parameter.
  • In the catch block catch exceptions for things when the file permissions are insufficient and file not existing exception.
  • Upon successful deletion print “file has been deleted”.

Program:

import java.io.*;
import java.nio.file.*;

public class Main
{
    public static void main(String[] args)
    {
        try
        {
            // Put the path into the function deleteIfExists()
            Files.deleteIfExists(Paths.get("E:\\New folder (2)\\New folder\\file.docx"));
        }
        // Catch exception if file does not exists
        catch(NoSuchFileException e)
        {
            System.out.println("File does not exist");
        // Catch exception if invalid permissions
        catch(IOException e)
        {
            System.out.println("Invalid Permissions");
        }
        // Prints on successful deletion
        System.out.println("Successfully Deleted");
    }
}

Output:

Successfully Deleted

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Program to Create a File and Write into the File

Java Program to Create a File and Write into the File

In this article we are going to see how we can create and write into a file by using Java programming language.

Java Program to Create a File and Write into the File

As per problem statement first we have to create a file in a specified path then we have to write into the created file.

Let’s see program to understand it clearly.

Method-1: Java Program to Create a File and Write into the File by Using Java IO Library

In this method we will be using the IO library. We will be creating two objects, one File object to create a new file and another FileWriter object to write into the file.

Approach

  • Create a File object with the file name as parameter.
  • Use the method createNewFile( ) of the File class to create a new file inside an If block which will print upon successful creation of the file.
  • Now create a FileWriter object with the same filename as parameter.
  • Write into the file using write( ) method of the FileWriter class.
  • Now close the file.
  • Use a catch block to catch any IO exceptions and print it.

Program:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Main
{
    public static void main(String[] args)
    {
    	//try blockcreateNewFile()
        try
        {
            //Create object of File class and pass file name as parameter
            File fileObj = new File("BtechGeeks.txt");
            //create the file by using inbuilt createNewFile() of File class
            if(fileObj.createNewFile())
            {
                System.out.println("File "+fileObj.getName() +" has been created");
            }

            //Create a writer object to write to the file & pass file name as parameter
            FileWriter writerObj = new FileWriter("BtechGeeks.txt");
            //Writing to the file
            writerObj.write("BtechGeeks is one of the best platform to learn Java");
            writerObj.close();
        }
        //Catch block
        catch(IOException e)
        {
            System.out.println("Unable to complete the task");
            // Print the exception occurred
            e.printStackTrace();
        }
        //Prints on successful creation and writing in the file
        System.out.println("Successfully File Created and Written into File");
    }
}

Output:

Console Output:

File BtechGeeks.txt has been created
Successfully File Created and Written into File

In File Explorer the file has been created:

Java-Program-to-Create-a-File-and-Write-into-the-File

Written text/content inside file:

 Java-Program-to-Create-a-File-and-Write-into-the-File

Method-2: Java Program to Create a File and Write into the File by Using FileOutputStream

In this method we will be again using the IO library.

Method Used:

  • getBytes( ): Convert the string characters into a byte array.
  • write( ): Takes byte array as parameter and writes it into the file.

Approach:

  • Create a FileOutputStream object with the file name.
  • Store the content to write in a string variable
  • Convert the string into a byte array using getBytes( ) method.
  • Now use the write( ) method of the file class with the byte array as parameter to write into the file.
  • Now close the file.

Program:

import java.io.*;

public class Main
{
    public static void main(String[] args)
    {
        //try block
        try
        {
            // Created a FileOutputStream object with the file name as parameter
            FileOutputStream file = new FileOutputStream("file.txt", true);
            // The text to write into the file
            String text = "Hello World";
            // Convert the string into bytes
            byte[] textByte  = text.getBytes();
            // Writing into the file
            file.write(textByte);
            file.close();
            System.out.println("File written successfully");
        }
        //Catch and print any IOException caused
        catch(IOException e)
        {
            System.out.println("Unable to create file. Exception - "+e);
        }
    }
}

Output:

In Console:

File written successfully

In File Explorer:

Java Program to Create a File and Write into the File by Using File Output Stream

Method-3: Java Program to Create a File and Write into the File by Using NIO

Java NIO package is also another package that handle IO operations and it  might seem a replacement to JavaIO but it is not. Both IO and NIO packages are used here together.

Approach:

  • Store the file path in a string variable
  • Now create a Path object to store the path
  • Create the file using Files.createFile() method using the path and store its path in another path object
  • Print the path of the object to the console
  • Now use a FileWriter object with the same path to create an object and write into the file
  • Close the file
  • Catch any exceptions if caused and print the error

Program:

import java.io.*;
import java.io.*;
import java.nio.file.*;

public class Main{
    public static void main(String[] args)
    {
        //Declare a string variable as assign the file path as value
        String filePath = "C:\\Users\\DELL\\eclipse-workspace\\BtechGeeks_File.txt";
        // Creating a Path object from the file path
        Path path = Paths.get(filePath);
        //try block
        try
        {
            //Creating a file by using createFile() method 
            //and storing its path in a path object p
            Path p = Files.createFile(path);
            // Printing the file path to console
            System.out.println("File created at "+p);

            //Creating a FileWriter object and writing to the file
            FileWriter file = new FileWriter(filePath,true);
            file.write("Hello World");
            file.close();

            System.out.println("Successfully wrote to the file");
        }
        //Catch and print any IOException caused
        catch(IOException e)
        {
            System.out.println("Unable to create file. Exception - "+e);
        }
    }
}

Output:

In Console:

File created at C:\Users\DELL\eclipse-workspace\BtechGeeks_File.txt
Successfully wrote to the file

In File Explorer:

Java-Program-to-Create-a-File-and-Write-into-the-File-by-Using-NIO

Written text/content in file:

Java-Program-to-Create-a-File-and-Write-into-the-File-by-Using-NIO

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Program to Create and Write into CSV File

Java Program to Create and Write into File

In this article we will see how you can create and write into CSV file by using Java programming language.

Java Program to Create and Write into CSV File

As per problem statement first we have to create an CSV file and then we have to write data into the file. We will do it without using any third party dependencies. Before jumping into the program let’s know what is CSV file first.

CSV file:

Comma Separated Value in short CSV, it is a file in which information is separated by commas. It can be represented in tabular format as well where each line refers to a data record.

Let’s see the program to understand it clearly.

Approach:

  • Create a String 2D array and along with elements(values).
  • Create object of File class and pass the CSV file name as parameter.
  • Create an object of FileWriter class and pass the File class object as parameter.
  • Then write data into file as comma-separated values in each line by using for loop.
  • Check the file has been created in the respective path and open it, you will see the data in it.

Program:

package btechgeeks;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Main 
{
    //Main method
    public static void main(String[] args) throws IOException 
    {
    	//try block
    	try
    	{
    	//declared a String 2D array and its values	
        String[][] users = {
                {"NAME", "AGE", "GENDER", "CITY"},
                {"Satya", "22", "MALE", "Bhubaneswar"},
                {"Rakesh", "26", "MALE", "Chennai"},
                {"Preeti", "21", "FEMALE", "Bokaro"},
                {"Saurav", "25", "MALE", "Noida"},
                {"Richa", "24", "FEMALE", "Bangalore"}
        };

        //Create object of File class and pass the CSV file name as parameter
        File csvFile = new File("StudentDetails.csv");
        //Create an object of FileWriter class and pass the File class object as parameter
        FileWriter fileWriter = new FileWriter(csvFile);

        //Writing data into file
        for (String[] details : users) 
        {
            StringBuilder sb= new StringBuilder();
            for (int i = 0; i < details.length; i++) 
            {
                sb.append(details[i]);
                if (i != details.length - 1) 
                {
                    sb.append(',');
                }
            }
            sb.append("\n");
            fileWriter.write(sb.toString());
        }
        //close the FileWriter class object
        fileWriter.close();
        System.out.println("CSV file created and data written into it successfully");
    	}
    	catch(Exception e)
    	{
    		System.out.println("Exception occured "+ e);
    	}
    }
}

Output:

In Console:

CSV file created and data written into it successfully

In File Explorer:

Created CSV file i.e. StudentDetails.csv

Java Program to Create and Write into CSV File

File Opened in Excel

Java Program to Create and Write into File

File Opened in Notepad

Java Program to Create and Write into File

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Program to Detect the Number Key Pressed

Java Program to Detect the Number Key Pressed

In this article we will see how you can detect which number key pressed by suing Java programming language.

Java Program to Detect the Number Key Pressed

As per the problem statement you will allow the user to enter any key and you have to detect that the pressed key is which digit. If user has pressed number keys from 0 to 9 then you have to detect that which number key has been pressed else if any other character key has been pressed then you have to tell ‘What you have entered that is not allowed’. If the user has entered more than one character then tell the user ‘You have entered more than one character’.

Let’s understand it with example.

User has pressed 8 key.
Output: You have pressed 8

User has pressed w key.
Output: What you have entered that is not allowed

User has pressed 5 key & 6 key  means 56
Output: You have entered more than one character

Let’s see the program to understand it more clearly.

Approach:

  • Declare an String variable say str.
  • Ask the user to enter any character (mostly ask to enter any digit).
  • Check if the length of user input value is more than one then print “You have entered more than one character” and return.
  • Else convert the String value to Character value and store it in an char type say ch.
  • Check the character is a digit or not by using isDigit() method of Character class.
  • If that character is a digit then print that number key has been pressed.
  • Else print ‘What you have entered that is not allowed’.

Program:

import java.lang.*;
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //ask the user to enter any digit
        System.out.println("Enter any digit:  ");
        //assigning the user input digit to a String variable
        String str = sc.next();
        
        //Checking the length of input String
        //If length is more than 1 that means you have entered more than one character
        if (str.length() >1)
        {
            System.out.println("You have entered more than one character"); 
            return;
        }
        
        //converting the String into an character
        char ch=str.charAt(0);
        
        //Checking the character is a digit or not
        boolean result = Character.isDigit(ch);
        
        //if input value is a digit then print the input value
        if(result) 
            System.out.println("You have pressed "+ch);
        //else print Not Allowed 
        else
            System.out.println("What you have entered that is not allowed");
    }
}

Output:

Case-1
Enter any digit: 
6
You have pressed 6

Case-2
Enter any digit: 
h
What you have entered that is not allowed

Case-3
Enter any digit: 
68
You have entered more than one character

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Program to Get the File Size

Java Program to Get the File Size

In this article you will see how you can get the size of file by using Java programming language.

Java Program to Get the File Size

Every file which is present in your system occupies some memory space to be stored in the system. File size tells about the amount of memory required for storing that file or in simple the file size is the amount of space taken by the file in the memory.

Let’s see program to understand it more clearly.

Method-1: Java Program to Get the File Size by Using File Class length() Method

In Java we have File class in java.io package. File class provides an inbuilt length() method to get the size of the specified file in bytes.

Approach:

  • Declare a String variable and assign the file path for which you want to know the file size.
  • Create an object of File class by passing file path as parameter.
  • Then check specified path or file is actually a file or not by using isFile() method and it is available in the specifies path or not by using exists() method. If that is not a normal file or not available in path then simply return.
  • Else get the size of file by using inbuilt length() method.

Program:

import java.io.File;

public class Main
{
    public static void main(String[] args) 
    {
        //declare a String variable filePath and assign the path of file 
        //for which file you want to know the size
        String filePath = "F:\\Tutorial IoT\\SDN Cisco PPT.pdf";
        //Create a object of File class and pass that filePath as parameter
        File file = new File(filePath);
        
        //Check if file does not exist by using inbuilt exists() method
        //or check if file is not a normal file type by using inbuilt isFile() method
        //then return 
        if (!file.exists() || !file.isFile()) 
            return;
        
        //else get the file size by using length() method of File class
        System.out.println("Your File size is: ");
        System.out.println("In Bytes: "+file.length() + " bytes");
        System.out.println("In KiloBytes: "+ file.length() / 1024 + "  kb");
        System.out.println("In MegaBytes: "+file.length() / (1024 * 1024) + " mb");
    }
}

Output:

Your File size is: 
In Bytes: 11261028 bytes
In KiloBytes: 10997 kb
In MegaBytes: 10 mb

Method-2: Java Program to Get the File Size by Using FileChannel Class size() Method

In Java we have FileChannel class in java.nio.channels package. FileChannel class provides an inbuilt size() method to get the size of the specified file in bytes.

Approach:

  • Declare a String variable and assign the file path for which you want to know the file size.
  • Create an object of Path class by passing file path as parameter.
  • Then create an object of FileChannel class by passing object of Path class as parameter.
  • Then get the size of file by using inbuilt size() method.

Program:

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main
{
    public static void main(String[] args) throws IOException 
    {
        //declare a String variable filePath and assign the path of file 
        //for which file you want to know the size
        String filePath = "F:\\Tutorial IoT\\SDN Cisco PPT.pdf";
        //Create a object of Path class and pass that filePath as parameter
        Path path = Paths.get(filePath);

        //Create an object of FileChannel class and pass the path as parameter
        //Inbuilt open() method returns a filechannel to access the file
        FileChannel fileChannel = FileChannel.open(path);
        //Get the size by using inbuilt size() method of FileChannel class
        long fileSize = fileChannel.size();
        System.out.println("Your file size: "+fileSize + " bytes");
        //Closing the filechannel
        fileChannel.close();
    }
}

Output:

Your file size: 11261028 bytes

Method-3: Java Program to Get the File Size by Using Files Class size() Method

In Java we have Files class in java.nio.file package. Files class provides an inbuilt size() method to get the size of the specified file in bytes.

Approach:

  • Declare a String variable and assign the file path for which you want to know the file size.
  • Create an object of Path class by passing file path as parameter.
  • Then create an object of Files class by passing object of Path class as parameter.
  • Then get the size of file by using inbuilt size() method.

Program:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main
{
    public static void main(String[] args) throws IOException 
    {
        //declare a String variable filePath and assign the path of file 
        //for which file you want to know the size
        String filePath = "F:\\Tutorial IoT\\SDN Cisco PPT.pdf";
        //Create a object of Path class and pass that filePath as parameter
        Path path = Paths.get(filePath);
        
        //Get the file size by using inbuilt size() method of File class
        long fileSize = Files.size(path);
        //print the file size
        System.out.println("Your file size: "+fileSize + " bytes");

    }
}

Output:

Your file size: 11261028 bytes

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Program to Check Internet Connectivity

Java Program to Check Internet Connectivity

In this article you will see how to check internet connectivity by using java programming language.

Java Program to Check Internet Connectivity

What is Internet?

Internet refers to the global network means global system of interconnected computer networks. It is also called as network of network. In short we say it only ‘net’. It allows us to connect with any other computer or network devices globally.

What is internet connectivity?

Internet connectivity refers to the technology through which we can connect to any network device and establish a communication with that device. By using computer terminals or network devices you can connect to internet and avail various internet services.

Let’s see the program to understand it more clearly.

NOTE: Please run the program on local machine and not on an online compiler to see the correct output.

Method-1: Java Program to Check Internet Connectivity By Using Java URL Class

Approach:

  • Create an object of URL class and pass the web link as parameter
  • Check the connection is getting established or not by using openConnection() method of URLConnection class.
  • If connection is getting established then Internet is connected else it will throw an exception and catch block will be executed which will print the result as internet is not connected.

Output:

package btechgeeks;

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

public class CheckInternetConnection 
{
        public static void main(String args[]) throws Exception
        {
        	try 
        	{
        		//Create an object of URL class and pass the web link as parameter
        	        URL obj = new URL("https://www.google.com");
        	        //Check the connection is getting established or not 
        	        //By using openConnection() method of URLConnection class
        	        URLConnection con = obj.openConnection();
        	        con.connect();   
        	 
        	        System.out.println("Internet Connection Available");   
        	            
        	 }
        	//if connection can't be established
        	//then internet is not connected
        	catch (Exception e)
        	{  
        	        System.out.println("No Internet Connection Available");     
        	                                                            
        	} 
        }
}

Output:

Internet Connection Available

Method-2: Java Program to Check Internet Connectivity By Using Java Runtime Class

Approach:

  • First get the run time object of running application by using getRuntime() method of Runtime class.
  • Check internet connectivity by running a simple ping to OpenDNS’s IP i.e 208.67.222.222.
  • You will get an output as 0 if the internet connection is available else you will get 1.
  • Them match the output by using an if condition, if the out put is 0 then print ‘Internet is connected’ else print ‘Internet is not connected’.

Output:

package btechgeeks;

import java.util.*;
import java.io.*;

public class CheckInternetConnection 
{
        public static void main(String args[]) throws Exception
        {
        	//By using  getRuntime() method test connectivity
            Process process = java.lang.Runtime.getRuntime().exec("ping -n 1 208.67.222.222");
            int output = process.waitFor();
            //output will be 0 if internet connectivity is available
            if (output == 0) 
            {
                System.out.println("Internet Connected, "
                                   + "Output is " + output);
            }
            //else output will be 1
            else 
            {
                System.out.println("Internet Not Connected, "
                                   + "Output is " + output);
            }
        }
}

Output:

Internet Connected, Output is 0

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Program to Generate and Verify OTP

Java Program to Generate and Verify OTP

In this article we will see how we can generate OTP(One Time Password) by using Java programming language.

Java Program to Generate OTP & Verify OTP

OTP:

One time Password in short known as OTP. It is a random set of numbers or characters which is used for security reason. To check the authentication instantly and correctly of the user, OTP is used where one OTP is shared with the user through any medium like message or mail and then it is validated.

Explanation:

In Java we have java.uti.Random class which is used to generate pseudorandom numbers. We have inbuilt random() method which can be used to generate random numbers.

Let’s see the program to understand it more clearly.

Program to Generate and Verify OTP:

Approach:

  • Call a user defined method say createOTP() method by passing length as parameter, which refers to length of OTP. And store the result of this method which is an OTP in a string variable say resultOTP.
  • Inside method by using a for loop create the OTP by using Random().nextInt(9) method, which will generate random digit within 0-9.
  • After the for loop completion you will get an OTP is which is stored in currentOTP string variable. Return currentOTP
  • Then ask the user to enter the system generated OTP and assign it to an String variable say inputOTP.
  • Then by using inbuilt equals() method compare both the OTP i.e. system generated OTP and user input OTP.
  • If both OTP matches then OTP verification successful else Invalid OTP.

Program:

import java.io.*;
import java.util.*;

public class Main 
{
    static String currentOTP = "";
    static String inputOTP = "";
    static int randomNo;
    
    //driver method
   public static void main(String[] args) 
   {
      //Object of Scanner class created
      Scanner sc=new Scanner(System.in);
      
      //calling the user defined method createOTP() 
      //and passing the OTP length as parameter
      //and assigning the result OTP to a character variable 
      String resultOTP=createOTP(4);
      System.out.println("Your OTP: "+resultOTP);
      
      //Ask the user to enter the OTP
      System.out.print("Enter received OTP: ");
      inputOTP = sc.nextLine();
      if (resultOTP.equals(inputOTP))
        System.out.println("OTP verified successfully");
      else
        System.out.println("Invalid OTP!");
   }

   private static String createOTP(int length) 
   {
        // Use for loop to iterate 4 times and generate random OTP
        for (int i = 0; i < length; i++) 
        {
            //Generating random digit within 0-9, which is of type int
            randomNo = new Random().nextInt(9);
            //converting generated randomNo to type String by using toString() method
            //then concating it to the currentOTP 
            currentOTP = currentOTP.concat(Integer.toString(randomNo));
        }
        //Return the generated OTP
        return currentOTP;
   }
}

Output:

CASE-1: Invalid OTP

Your OTP: 0855
Enter received OTP: 0856
Invalid OTP!

CASE-2: Valid OTP

Your OTP: 7271
Enter received OTP: 7271
OTP verified successfully

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.