Author: admin

  • Java Program to Read Char by Char from a File

    In this tutorial, you will learn how to Read Char by Char from a File in java. To understand it better, you may want to check the following first:


    Java Program to Read Char by Char from a File

    First, save the content in a text file with the same name that you enter in a program.
    For this example, a text file saved with the name javaCode.txt

    javaCode.txt

    Welcome to Simple2Code program

    //read char by char from a file 
    
     import java.io.*;
    
     public class ReadCharByChar
     {
      public static void main(String[] args) throws IOException 
      {
        File f = new File("javaCode.txt");   
        
        FileReader fr=new FileReader(f);  
        BufferedReader br=new BufferedReader(fr);
          
        int c = 0;             
        
        while((c = br.read()) != -1)  //Read char by Char
        {
          char character = (char) c;    //converting integer to char
          System.out.println(character); //Display
        }
          
      }
     }

    Output:

     W
     e
     l
     c
     o
     m
     e
    
     t
     o
    
     S
     i
     m
     p
     l
     e
     2
     C
     o
     d
     e
    
     p
     r
     o
     g
     r
     a
     m

  • Java Program to Count the Number of Words in a File

    In this tutorial, you will learn how to Count the Number of Words in a File in java. To understand it better, you may want to check the following first:


    Java Program to Count the Number of Words in a File

    First, save the content in a text file with the same name that you enter in a program.
    For this example, a text file saved with the name javaCode.txt

    javaCode.txt

    Welcome to Simple2Code.
    Let Start
    first tutorial
    second Program

    //count number of words in a file 
    
     import java.io.*;
    
     public class WordCount
     {
      public static void main(String[] args) throws IOException 
      {
        File f = new File("javaCode.txt"); //creating txt file
        
        String[] words=null;  //Intializing
        
        int wordCount = 0;     //Intializing word count 
        FileReader fr = new FileReader(f);    //Creation of File Reader object
        BufferedReader br = new BufferedReader(fr);  //Creation of BufferedReader object
        String s;
        while((s = br.readLine())!=null)   //Reading Content from the file
        {
          words = s.split(" ");   //Split the word using space
          wordCount = wordCount + words.length;   //increment in word count for each word
        }
        fr.close();
        System.out.println("Number of words in the file:" +wordCount);  //Display
      }
     }

    Output:

    Number of words in the file:9


  • Java Program to Count the Number of Lines in a File

    In this tutorial, you will learn how to Count the Number of Lines in a File in java. To understand it better, you may want to check the following first:


    Java Program to Count the Number of Lines in a File

    First, save the content in a text file with the same name that you enter in a program.
    For this example, a text file saved with the name javaCode.txt

    javaCode.txt

    Welcome to Simple2Code.
    Let Start
    first tutorial
    second Program

    Source Code:

    //count number of lines in a file
    
     import java.io.BufferedReader;
     import java.io.File;
     import java.io.FileReader;
     import java.io.IOException;
     
     public class LineCount 
     {
      public static void main(String[] args) throws IOException 
      {
        File f = new File("javaCode.txt");
        int count=0;   
            
        FileReader fr = new FileReader(f);  
        BufferedReader br = new BufferedReader(fr); 
        
        String s;         
            
        while((s=br.readLine())!=null) //Reading Content 
        {
          count++; //increases for each line
        }
        fr.close();
        //Display number of line
        System.out.println("Total number of line:"+count); 
      }
     
     }

    Output:

    Total number of line: 4


  • Java Program to Copy Content from one File to another File

    In this tutorial, you will learn how to copy the content of one file to another in java. Here the new file is created where the content of another file is copied to this newly created file.


    Java Program to Copy Content from one File to another File

    First, save the content in a text file with the same name that you enter in a program.
    For this example, a text file saved with the name javaCode.txt

    javaCode.txt

    Welcome to Simple2Code.
    Let Start
    first tutorial
    second Program

    And after the execution new file will be created as named copiedJavaCode.txt. And the content will be copied to this text file.

    Source Code:

     //copy content from one to another file 
    
     import java.io.*;
    
     public class CopyFile
     {
        public static void main(String[] args) throws IOException 
      {
          File f1 = new File("javaCode.txt");      //saved file
          File f2 = new File("copiedJavaCode.txt");   //destined file
          
          FileReader fr = new FileReader(f1);      //file reader object 
          BufferedReader br=new BufferedReader(fr);  //buffer reader object
          FileWriter fw= new FileWriter(f2); //file writer object 
          
          String s=null;
          
          while((s = br.readLine())!=null) //Copying Content to the new file
          {
            fw.write(s);
            fw.write("\n");
            fw.flush();
          }
            fw.close();
            
          System.out.println("Successfully Copied.");
          System.out.println("Check the copiedJavaCode.txt.");
        }
     
     }

    Output: After execution check your copiedJavaCode.txt file where all the content is copied from javaCode.txt file.

    Successfully Copied.
    Check the copiedJavaCode.txt.


  • Java Program to Check Whether a New file is Created or Already Exists

    In this tutorial, we will write a program to check whether a new file is created or already exists in java. This java program check if the file is already created in that particular directory or it is already present.

    The program also uses try and catch for exception handling. If you want to learn about Java files and Exceptions, click the link below.


    Java Program to Check Whether a New file is Created or Already Exists

    //check whether new file is created or already exists 
    
     import java.io.*;  
     public class FileCreated 
     {  
      public static void main(String[] args) 
      {  
    
        try {  
          File file = new File("javaCode.txt");  
          if (file.createNewFile()) {  
              System.out.println("New File is created.");  
          } else {  
              System.out.println("File already exists.");  
          }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    
      }  
     }

    Output:

    New File is created.

    A new file will be created in the same directory.


  • Java Program to Append Content into a File

    This tutorial shows you how to append Content into a file in java.

    Append means to add something at the end. Similarly, the following java program adds new Content into a file. File in-built function append() is used to add new content at the end.

    If you do not about the file system in java then click the link below.


    Program to Append Content into a File in Java

     //append content into a file 
    
     import java.io.File;
     import java.io.FileWriter;
     import java.io.IOException;
     
     public class FileAppend
     {
      public static void main(String[] args) throws IOException 
      {
        File f = new File("javaCode.txt");     
        FileWriter fw = new FileWriter(f,true);  //Create filewriter object
    
        fw.append("Welcome to Simple2Code\n");  //Append the Content 
    
        fw.flush();          
        fw.close();
    
        System.out.println("Check javaCode.txt.")
      }
     
     }

    Output:

    Check javaCode.txt.

    Open the file that will be created in the same directory after execution.
    javaCode.txt

    Welcome to Simple2Code.


  • Java Program to Find the Number of Vowels and Consonants in a String

    The program to find the number of vowels and consonants present in a String in java is simple. It checks each of the characters in strings and compares it with vowels (i.e. a, e, i, o, u).

    When the program finds the character equals to vowel then it increases the vow integer else cons integer increases. And at last, the result is displayed.

    You may also take the user input instead of declaring the String in a Program. Following the below to take a user input.


    Java Program to Find the Number of Vowels and Consonants in a String

     //number of vowels and consonants in a string 
    
     public class CountVowelConsonants
     {
       public static void main(String[] args)
       {
         String str = "Learning To Code";
         int vow = 0, cons = 0;
         str = str.toLowerCase();
    
         for (int i = 0; i < str.length(); ++i)
         {
           char ch = str.charAt(i);
           if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
           {
             ++vow;
           }
           else if ((ch >= 'a' && ch <= 'z'))
           {
             ++cons;
           }
         }
    
         System.out.println("Number of Vowels : " + vow);
         System.out.println("Number of Consonants: " + cons);
       }
     }

    Output:

    Number of Vowels : 6
    Number of Consonants: 8


  • Java Program to Count Total Character in a String

    In this tutorial, we will see how to Count Total Characters in a String in java.

    The program below counts the number of letters present in the sentence (String) and displays the total character present in number.

    The program checks for spaces present in the Strings and if gets space while checking each character then it will skip the spaces, charAt() function is used in the following java program.

    Although if you want to know about the String and loop that are used in the program below. you may click the link below:

    We will see two Example:

    1. Where the String is already defined in the program.
    2. Where the string is taken as an input from the user.


    1. Program to Count Total Character in a String in Java

     //count total character in a string
    
     public class CountCharString
     {    
      public static void main(String[] args) 
      {    
        String str = "I am learning java";    
        int count = 0;  
          
        //counting String
        for(int i = 0; i < str.length(); i++) 
        {    
          if(str.charAt(i) != ' ')    
              count++;    
        }    
              
        //Displays the total character, space exclused    
        System.out.println("Total character in a given string: " + count);    
      }    
     }

    Output:

    Total character in a given string: 15


    2. Program to Count Total Character in a String in Java

    We will see the example where we will get the String from the user inputs in the program as shown below:

    //count total character in a string (user inputs)
     
     import java.util.Scanner;
    
     public class CountCharString
     {    
       public static void main(String[] args) 
       {    
         String str;    
         int count = 0;  
         
         Scanner in = new Scanner(System.in);
      
          //User Input
          System.out.println("Enter a string: ");
          str = in.nextLine();
                 
          //Excluding Space  
          for(int i = 0; i < str.length(); i++) 
          {    
             if(str.charAt(i) != ' ')    
                count++;    
          }    
                 
          //Displays the total character, space exclused    
          System.out.println("Total character in a entered string: " + count);    
         }    
     }

    Output:

    Enter a string:
    I am learning java
    Total character in a entered string: 15


  • Java Program to Find the Frequency of a Character

    In this tutorial, we will write a program to calculate the frequency of Characters present in a String in java.

    Frequency refers to the number of times that have occurred. In this program, we will count how many times each character is repeated in a String and display the result for each word’s frequency.

    The program splits each word with space count present after every word, toCharArray() function is used in the following java program.

    Although if you want to know about the String and loop that are used in the program below. you may click the link below:

    We will see two examples:

    1. Where the String is already defined in the program.
    2. Where the string is taken as an input from the user.


    1. Program to find the frequency of Words in Java

    //find a frequency of a character 
    
    public class FrequencyOfCharacter
    {
      public static void main(String[] args)
      {
        int i, j;
        String str = "Beautiful Beach";
        int[] frequency = new int[str.length()];
    
        char string[] = str.toCharArray();
    
        for (i = 0; i < str.length(); i++)
        {
          frequency[i] = 1;
          for (j = i + 1; j < str.length(); j++)
          {
            if (string[i] == string[j])
            {
              frequency[i]++;
    
             	//Set string[j] to 0  
              string[j] = '0';
            }
          }
        }
    
        //Displays the characters with their frequency    
        System.out.println("Following Lists the characters and their frequency:");
        for (i = 0; i < frequency.length; i++)
        {
          if (string[i] != ' ' && string[i] != '0')
            System.out.println(string[i] + "->" + frequency[i]);
        }
      }
    }

    Output:

    Following Lists the characters and their frequency:
    B->2
    e->2
    a->2
    u->2
    t->1
    i->1
    f->1
    l->1
    c->1
    h->1

    2. Program to find the frequency of Words in Java, user’s input

    //find a frequency of a character 
    
    import java.util.Scanner;
    
    public class FrequencyOfCharacter
    {
      public static void main(String[] args)
      {
        int i, j;
        String str;
        Scanner sc = new Scanner(System.in);
    
        //User Input
        System.out.println("Enter a string: ");
        str = sc.nextLine();
    
        int[] frequency = new int[str.length()];
    
        char string[] = str.toCharArray();
    
        for (i = 0; i < str.length(); i++)
        {
          frequency[i] = 1;
          for (j = i + 1; j < str.length(); j++)
          {
            if (string[i] == string[j])
            {
              frequency[i]++;
    
              //Set string[j] to 0  
              string[j] = '0';
            }
          }
        }
    
        //Displays the characters with their frequency    
        System.out.println("Following Lists the entered characters and their frequency:");
        for (i = 0; i < frequency.length; i++)
        {
          if (string[i] != ' ' && string[i] != '0')
            System.out.println(string[i] + "->" + frequency[i]);
        }
      }
    }

    Output:

    Enter a string: 
    Beautiful Beach
    Following Lists the characters and their frequency:
    B->2
    e->2
    a->2
    u->2
    t->1
    i->1
    f->1
    l->1
    c->1
    h->1

  • Java Program to Find a Frequency of Words

    In this tutorial, we will see how to calculate the frequency of words present in a String in java.

    Frequency refers to the number of times that have occurred. In this program, we will count how many time each word are repeated and display the result for each word’s frequency.

    The program splits each word with space count present after every word, split() and equals() functions are used in the following java program.


    Java Program to Find a Frequency of Words

    //find a frequency of words
    
     public class RepeatedWord
     {
     
      public static void main(String[] args)
      {
          String input="Welcome to java java Simle2code to java";  //String
          
          String[] words = input.split(" ");  //Split the word from String
          int wc = 1;    //word count initiated
          
          for(int i=0; i < words.length;i++)  
          {
            for(int j = i+1; j < words.length;j++) 
            {
             if(words[i].equals(words[j]))  //Checking for both strings are equal
             {
               wc = wc+1;    //if equal increment the count
               words[j]="0"; //Replace repeated words by zero
             }
            }
            if(words[i]!="0")
            System.out.println(words[i]+"--"+wc); //Display
            wc=1;
            
          }  
      }
    }

    Output:

    Welcome--1
    to--2
    java--3
    Simle2code--1