Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to read a text file through Java program. ?

Introduction

Hello friends, Lets begin with another source code in java with example and explanation. Today, I am posting a hub on Java Source Code category with program "How do I read a text file in Java "?. Learning Java by example is fun. To run below code you must have JDK installed along with some basic knowledge, How to compile a Java program ?. , How to run a Java program.? and some basic Java fundamentals. Lets begin first writing the source code and then explaining the code step-by-step in a tutorial form.
Given below is the snap shot of the student.txt file from which our source code reads the data and prints out to console window. Remember the path given in the program as "E:\\student.txt" is the path where I have kept student.txt file. You can place the file wherever you want on your machine, but just replace the path in the Java program to yours.

Snap Shot of Student.txt file to read data




How do i read text file in Java ?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Reader {
    public static void main(String[ ] args) {
        File file = new File("E:\\student.txt");       
        BufferedReader reader = null;
        StringBuilder line = new StringBuilder();

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            
            while ((text = reader.readLine()) != null) {
               line.append(text)
               .append(System.getProperty("line.separator"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(line.toString());
    }
}

Snap shot of the output on console window






Working of Example



Lets look at the code above line by line. I will be explaining you what each line does. I will be taking you with little-little snippets and explaining overall functionality of the source code. Line 1 to 5 - Basically it contains import statements for the classes required by our source code to get executed by printing the text. The imports are generally from the I/O package libraries. Our code uses these classes in the program below. Some of them are main classes of I/O package such as BufferedReader, File, FileReader, FileNotFoundException and IOException. Line 9 to 11 - If we look at line 9, we will find that a new file is created on the path "E:\\student.txt", if no file exists. But in our case file is already placed on the path with some content written on it. This file we gave as a string to just create an object of class File not a file on system. Line 10 creates a null BufferedReader object. Generally BufferedReader is an class which acts as a buffer to hold chunks of character data. This class we need because its fast and it reads character data fast with large chunks of storage.Line 11 we create a StringBuilder object because this variable will store all the data present in student.txt document and prints it on the console. Line 13 to 15 :- Line 13 starts with a try-catch-finally block, generally when we deal with the I/O files many exceptions can occur. To catch such exceptions we must put our code in try-catch-finally block. Line 14 we create a BufferedReader object which wraps up a newly created FileReader object to which holds our File object to read the data. Generally FileReader object can read stream of characters from a file. FileReader can read characters from the student.txt file provided to it by File object. Line 15 creates a null string with a text variable , this variable is temporary placeholder or say counter for the next while loop. It will hold chunk of character on which while loops places a test condition. Line 17 to 19 :- Line 17 starts with a while loop. As we have access to file student.txt by FileReader object to read the file and its wrapper class BufferedReader class which holds FileReader class to process information transfer and storage fast. while loop applies looping on Counter variable text which holds the line by line data of character. This line of characters is been provided to text variable by method called as readLine() defined in BufferedReader class. This method reads and outputs character with one full line. The test condition in while loop makes it loop till text variable outputs null. On line 18 and 19 each loop will hold one-one line of characters in line variable by append() method. Generally append() method is defined in StringBuilder class which performs the task to append two strings together. As soon as one line gets stored in line variable we need one line separator which shifts line variable to hold string now from next line. So to get that line separator we put code that places line separator by the System properties called as line.separator. Line 21 to 25 :- Here we used try-catch statement because there may come a exception when say file student.txt is not found on the path specified in the code i.e 'E:\\student.txt', so it throws FileNotFoundException. If there is any exception occured while transferring of characters IOException may occur. Line 26 to 34 :- Generally try-catch-finally occur together. Here finally is optional but most important, it gets executed once in code whether exception occurs or not. All the resource releasing code is written in finally block. Since BufferedReader object holds critical resource for I/O operation, we should release it in our code. Its generally good practice to release the critical resources. Line 35 : - After all iterations and appending of characters line-by-line in line variable , we use print statement to print all the character of file on the console.

How to create and run a simple Java Program ?.

Introduction
Hello friends, Lets begin our hub with a simple Java program that prints or displays a message on Console as "Welcome Java Programs on Hubpages!". If we go in basics a Console is nothing but a simple display device of computer, where we can even put text that is input to program. Lets look at the program code that displays the text we want.

WelcomeJavaPrograms.java

public class WelcomeJavaPrograms {
  public static void main(String[ ] args){
    System.out.println("Welcome Java Programs on Hubpages!");   
  }
} 




Output of the program
Line 1 :- It starts by defining a class by the name WelcomeJavaPrograms. In Java programming language every program whether small or large must start with atleast one class. If we follow the naming convention of classes in Java, we have to name the class starting with an Uppercase letters. Important thing to note here is class name should match with the source file name which you will be using to store the code. So in our case above the source file name where above code goes must be WelcomeJavaPrograms.java. The entire class definition should come between opening and closing curly braces that is between { }.  Line 2 :- It starts by defining a method named as main. The main method is the entry point for all Java programs. Each program small or large, if you want to execute you should have a method named main in there. The execution point starts from there, as JVM (Java Virtual Machine) first searches the main method. If we look into what is a method ? . We can analyze it as block of statements that needs to be executed step-by-step. When we look into our example program we see that main method has only statement to execute that is System.out.println statement. Generally not going into much deep as of now just have an idea that this statement displays message "Welcome Java Programs on Hubpages!" on the console window. After each statement in Java we usually place a semi-colon to indicate compiler that particular statement is ended there. In above simple program many keywords are been used as class, public, main, static and void. These keywords have a special or significance meaning to compiler. Compiler understand what a particular keyword does in a program. Here if we look into the details of public keyword, it is an modifier which generally controls class or method visibility to other classes. When we declare public infront of class or method than that class or method are accessible by other classes which are outside. If we use keyword as private than its working is quite opposite to public keyword and it makes class or method private to code which is been defined outside the class. In our program above main method is been declared as public because it is been accessed by the code outside of the class. If we use static keyword before main method, we mean that main method is static and gets called without having to instantiate or making objects of the class. Since main method is been called by Java Virtual Machine no objects are needed for calling the main method. The last void keyword just gives the compiler information that main method would not return any value to the Java Virtual machine. Generally when we call any method we might have to pass some information to the method, which it uses to execute some statements. We usually pass this information as a parameters within the angle brackets of the method. If there are no parameters we define method with empty angle brackets i.e (). In our above program main method requires a argument which is String array named as String[] args having name of the parameter as args. This String of array receives information of the command line which it needs when executing the main method.   Line 3:- Brief understanding about the System.out.println() method, generally println method prints the string passed to it. System is a class which has access to the system and out is the output stream which connects the console and calls println method which prints the message to the console passed to it as argument.   Line 4:- It starts with a Java comment. Comments are very much important in each and every Java program. Comments allow us to place information about program in code. Generally its been avoided by the compiler and has no effect on execution of Java program. Usually it helps in debugging the code and helps other programmers to understand the code without going through whole code. In Java there are single-line comment and multi-line comment. Single-line comment usually starts with a two forward slashes (//). Multi-line comments are in between /* and */. Whenever compiler upon compilation of program sees // it avoids all written text after that on the same line. Whenever compiler sees /*, it tries to find */ and ignores all the code between them. T Let us look at examples of single-line comment and multi-line comment: // I am new to Hubpages, please help me!. /* I am writing my first Java program on Hubpages kindly have a look and comment. */ In Java block generally is a group of statements and starts by { and ends by }. Every program in Java has a block which encloses a class and also methods have there own blocks that to starts and ends with { and }. In every Java program each and every opening braces must have its closing brace. Java is a case-sensitive language, so writing class keyword as Class would result in compilation error. There are many syntax rules that Java follows and if you fail to obey those rules than on compiling program you will get compilation errors. Generally, missing of braces, missing of semi-colons, mistyping of keywords would result in compilation errors.

How to Create, Compile and Execute a Java program

Introduction : -
Java is extensively used programming language. It is been loved by many programmers from beginners to experts. Java is surely programming language of the future. If we look into the phases of program development, we come across many phases such as:





Step 1 : Creation of a Java program :-
By creating of a Java program we mean of writing of a Java program on any editor or IDE. This includes modifying of the program on editor, even after program has been written once. Creation of a Java program is not limit to only write program on editor and than leave it. Generally, creating of a Java program means writing a program on a editor or IDE, making all the corrections needed and than saving the program on secondary storage device as hard drive. After creating a Java program you should provide .java extension to file. It signifies that the particular file is a Java source code. Also , whatever progress we do from writing, editing , storing and providing .java extension to a file , it basically comes under creating of a Java program.

















Step 2 : Compiling a Java Program
Our next step after creation of program is the compilation of Java program. Generally Java program which we have created in step 1 with a .java extension, it is been compiled by the compiler. Suppose if we take example of our program say WelcomeJavaPrograms.java, when we want to compile this we use command such as javac. We can call it as The Java compiler. After opening command prompt or shell console we compile Java program with .java extension as
javac WelcomeJavaPrograms.java.

After executing the javac command, if no errors occur in our program we get a .class file which contains the bytecode. It means that the compiler has successfully converted Java source code to bytecode. Generally bytecode is been used by the JVM to run a particular application. Java Virtual Machine or JVM is a virtual machine that lies between our bytecode and underlying operating system. The final bytecode created is the executable file which only JVM understands.


















Java source code with .java extension is the high level programming language that only a programmer understands. While bytecode produced after compilation is the low-level language that only JVM understands. JVM is implemented on many operating systems which helps programmer to just compile program once, because the same .class file can be executed on different platforms with same JVM. This portion also provides portabilty feature, that you don't have to write again-and-again Java source code for the different platforms. As Java compiler is invoked by javac command, the JVM is been invoked by java command. On the console window you have to type :

java WelcomeJavaPrograms
This command will invoke the JVM to take further steps for execution of Java program.






















Step 3 : Program loading into memory by JVM:-
JVM requires memory to load the .class file before its execution. The process of placing a program in memory in order to run is called as Loading. There is a class loader present in the JVM whose main functionality is to load the .class file into the primary memory for the execution. All the .class files required by our program for the execution is been loaded by the class loader into the memory just before the execution.


































Step 4: Bytecode Verification by JVM :-
In order to maintain security of the program JVM has bytecode verifier. After the classes are loaded in to memory , bytecode verifier comes into picture and verifies bytecode of the loaded class in order to maintain security. It check whether bytecodes are valid. Thus it prevent our computer from malicious viruses and worms.












Step 5 : Execution of Java program : -
Whatever actions we have written in our Java program, JVM executes them by interpreting bytecode. If we talk about old JVM's they were slow, executed and interpreted one bytecode at a time. Modern JVM uses JIT compilation unit to which we even call just-in-time compilation. These compilers executes several instructions in parallel. They are also called as Java HotSpot compiler because JVM uses them to find hot spots in bytecode. By the term hot spots we mean that JVM analyze bytecode by searching those spots in program which are executed frequently. These frequent executable bytecodes parts are being translated to faster machine language code by Java HotSpot compiler. Now the significance behind this is whenever JVM encounter such parts again in bytecode it processes machine language code which are much faster as compared to execution of one byte code at a time.If we analyse above steps , we will find that there are two compilation phases. One in which source code is translated to bytecodes and second when hot spot parts of bytecodes are translated to machine language.

































Video Tutorial for above post :- 


 
© 2021 Learn Java by Examples Template by Hubberspot