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 Program for String Operations

In this article we are going to see a menu driven string application by using Java program.

Java Menu Driven Program for String Operations

We will design a menu driven program for 4 String operations. Like this you can add more String operations as well.

  1. String Length
  2. Concatenating two strings
  3. Compare two strings
  4. Trim a string

User Defined Methods Used:

  • len( ) – To find the length of the string
  • concatenate( ) – Add two strings
  • compareStr( ) – Compare two strings
  • trimStr( ) – Trim whitespaces

Approach:

  • In Driver method, take a while loop display all the methods.
  • Ask the user to enter the choice.
  • Use switch case for navigation.
  • To find length of a string we will call the user defined method len( ) function. This function takes the string as input and then using inbuilt length() method of the string library to print the length of the string period.
  • To concatenate two strings we will call the user defined method concatenate( ) which asks the user to input two strings and then concatenate strings(using inbuilt concat() library method) and store it in another variable.
  • To compare two strings, call user defined method compareStr( ) which compares two Strings by using inbuilt equals() method and returns a True if both String matches else returns False value.
  • To trim a string call user defined trimStr( ). This method takes in one string and then uses the string library trim() method to trim the whitespaces from the string.

Program:

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

public class Main
{
    static String s,s1,s2;
    static Scanner sc = new Scanner(System.in); 
    
    //Find length of a String
    static void len()
    {
        sc.nextLine();
        System.out.println("Enter the string");
        s=sc.nextLine();
        System.out.println("The string length is "+ s.length());
    }

    //Concatenate two Strings
    static void concatenate()
    {
        sc.nextLine();
        System.out.println("Enter First string to concat");
        s = sc.nextLine();
        System.out.println("Enter Second string to concat ");
        s1 = sc.nextLine();
        // Concatenating string s and s1 and storing in s2
        s2 = s.concat(s1);
        System.out.println("The concatenated string of "+s+" and "+s1+" is "+s2);
    }
    
    //Compare two Strings
    static void compareStr()
    {
        sc.nextLine();
        System.out.println("Enter First string to compare");
        s = sc.nextLine();
        System.out.println("Enter Second string to compare");
        s1 = sc.nextLine();
        // b stores the comparison result
        boolean b = s.equals(s1);
        if(b)
            System.out.println("The strings "+s+" and "+s1+ " are equal.");
        else
            System.out.println("The strings "+s+" and "+s1+ " are not equal.");
    }
    
    //Trimming spaces from String
    static void trimStr()
    {
        sc.nextLine();
        System.out.println("Enter string to trim");
        s=sc.nextLine();
        // Storing the trimmed string in s1
        s1= s.trim();
        System.out.println("The string "+s+" after trimming is "+s1);
    }
    
    //Driver method
    public static void main(String []args)
    {
        int ch; 
        while(true)
        {
            System.out.println("---\t String Operations\t---");
            System.out.println("1: Find the length Of String");
            System.out.println("2: Concatenate two strings");
            System.out.println("3: Compare two strings");
            System.out.println("4: String Trimming");
            System.out.println("5: Quit");
            System.out.print("Enter your choice: ");  
            ch = sc.nextInt();
            switch (ch)
            {
                case 1:len();
                    System.out.println("\n");
                    break;

                case 2:concatenate();
                    System.out.println("\n");
                    break;

                case 3:compareStr();
                    System.out.println("\n");
                    break;

                case 4: trimStr();
                    System.out.println("\n");
                    break;

                case 5:
                    System.exit(0);

                default: System.out.println("Invalid choice! Retry");
            }
        }

    }
}

Output:

--- String Operations ---
1: Find the length Of String
2: Concatenate two strings
3: Compare two strings
4: String Trimming
5: Quit
Enter your choice: 1
Enter the string
BtechGeeks
The string length is 10


--- String Operations ---
1: Find the length Of String
2: Concatenate two strings
3: Compare two strings
4: String Trimming
5: Quit
Enter your choice: 3
Enter First string to compare
Exception
Enter Second string to compare
Error
The strings Exception and Error are not equal.


--- String Operations ---
1: Find the length Of String
2: Concatenate two strings
3: Compare two strings
4: String Trimming
5: Quit
Enter your choice: 2
Enter First string to concat
Btech
Enter Second string to concat 
Geeks
The concatenated string of Btech and Geeks is BtechGeeks


--- String Operations ---
1: Find the length Of String
2: Concatenate two strings
3: Compare two strings
4: String Trimming
5: Quit
Enter your choice: 4
Enter string to trim
BtechGeeksBest
The string BtechGeeksBest after trimming is BtechGeeksBest


--- String Operations ---
1: Find the length Of String
2: Concatenate two strings
3: Compare two strings
4: String Trimming
5: Quit
Enter your choice: 4
Enter string to trim
India 
The string India after trimming is India


--- String Operations ---
1: Find the length Of String
2: Concatenate two strings
3: Compare two strings
4: String Trimming
5: Quit
Enter your choice: 5

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.

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 Print Happy Birthday on Your Birthday

Java Program to Print Happy Birthday on Your Birthday

In this article we will see how to print ‘Happy Birthday’ on your birthday by using Java programming language.

Java Program to Print Happy Birthday on Your Birthday

Birthday is the anniversary of the day on which the person was born. Generally people celebrate this day to with family, friends, cakes, gifts and many more surprises to make it memorable. That day starts with a warm wish like ‘Happy Birthday’ and many more.

Here we will write a Java program to check our birthday and print ‘Happy Birthday’.

Method-1: Java Program to Print Happy Birthday on Your Birthday By Using == Operator

Approach:

  • Declare birth date and month.
  • By using LocalDate class get the current date.
  • Call getDayOfMonth() and getMonth() method by using object of LocalDate class to get the current month and day.
  • Compare the user declared date and month with current date and month by using == operator.
  • If both date and month matches then it’s birthday else it’s not birthday.

Program:

import java.util.Scanner;
import java.time.LocalDate;
import java.time.Month;

public class Main
{
    public static void main(String args[]) 
    {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //Asking user to enter his/her name
        System.out.println("Enter your name: ");
        String name=sc.nextLine();
        //birth date 
        int birthDate = 21;
        //birth month
        Month birthMonth = Month.JULY;
        //current date
        LocalDate current_date = LocalDate.now();
        
        System.out.println("Today's Date: " + current_date);
        System.out.println("The birth Date: " +birthDate + " " +birthMonth);
        
        //getting current month
        int date = current_date.getDayOfMonth();
        //getting current month
        Month month = current_date.getMonth();
        
        if(date == birthDate && month == birthMonth) 
        { 
            System.out.println("Happy Birthday To You "+ name);
        } 
        else 
        { 
            System.out.println(name+" today is not your birthday");
        } 
    }
}

Output:

Enter your name: 
Satya
Today's Date: 2022-07-21
The birth Date: 21 JULY
Happy Birthday To You Satya

Method-2: Java Program to Print Happy Birthday on Your Birthday By Using compareTo() Method

Approach:

  • Create object of SimpleDateFormat class and pass parameter as MM-dd format.
  • Declare birth date in MM-dd format.
  • Get today’s date in MM-dd format.
  • Take a if condition and by using compareTo() method compare today’s date and birth date.
  • If condition satisfies then it’s birthday else it’s not birthday.

Program:

import java.util.Scanner;
import java.time.LocalDate;
import java.time.Month;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main
{
   public static void main(String[] args) throws ParseException 
   {
      //Scanner class object created 
      Scanner sc=new Scanner(System.in); 
      //Asking user to enter his/her name 
      System.out.println("Enter your name: "); 
      String name=sc.nextLine();
      
      //created object of SimpleDateFormat class
      //date format in MM-dd
      SimpleDateFormat s = new SimpleDateFormat("MM-dd");
      
      //today's date
      Date today = s.parse("07-21");
      //birth date
      Date birthDate = s.parse("07-21");
      
      System.out.println("Your birth date is 21st July");
      
      //comparing today's date and birth date
      if (today.compareTo(birthDate) == 0) 
      {
    	  System.out.println("Happy Birthday To You "+ name);
      }      
      else 
      {
    	  System.out.println(name+" today is not your birthday");
      }
   }
}

Output:

Enter your name: 
Satya
Your birth date is 21st July
Happy Birthday To You Satya

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.