File Handling in Java
In Java, a File is an abstract data type. A named location used to store related information is
known as a File. There are several File Operations like creating a new File, getting
information about File, writing into a File, reading from a File and deleting a File.
Stream: A series of data is referred to as a stream. In Java, Stream is classified into two
types, i.e., Byte Stream and Character Stream.
Byte Stream: Byte Stream is mainly involved with byte data. A file handling process with a
byte stream is a process in which an input is provided and executed with the byte data.
Character Stream: Character Stream is mainly involved with character data. A file
handling process with a character stream is a process in which an input is provided and
executed with the character data.
File Operations: We can perform the following operation on a file:
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
Create a File: Create a File operation is performed to create a new file. We use
the createNewFile() method of file. The createNewFile() method returns true when it
successfully creates a new file and returns false when the file already exists.
File to understand how we can use the createNewFile() method to perform this
operation.
CreateFile.java
. // Importing File class
. import java.io.File;
. // Importing the IOException class for handling errors
. import java.io.IOException;
. class CreateFile {
. public static void main(String args[]) {
. try {
. // Creating an object of a file
. File f0 = new File("D:FileOperationExample.txt");
. if (f0.createNewFile()) {
. System.out.println("File " + f0.getName() + " is created su
ccessfully.");
. } else {
. System.out.println("File is already exist in the directory.");
. }
. } catch (IOException exception) {
. System.out.println("An unexpected error is occurred.");
. exception.printStackTrace();
. }
. }
. }
Write to a File
. import java.io.FileWriter;
.
. // Importing the IOException class for handling errors
. import java.io.IOException;
.
. class WriteToFile {
. public static void main(String[] args) {
.
. try {
. FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
. // writing the content into the FileOperationExample.txt file
. fwrite.write("A named location used to store related information is referred to as a File.");
.
. // Closing the stream
. fwrite.close();
. System.out.println("Content is successfully wrote to the file.");
. } catch (IOException e) {
. System.out.println("Unexpected error occurred");
. e.printStackTrace();
. }
. }
. }
Read from a File:
. // Importing the File class
. import java.io.File;
. // Importing FileNotFoundException class for handling errors
. import java.io.FileNotFoundException;
. // Importing the Scanner class for reading text files
. import java.util.Scanner;
.
. class ReadFromFile {
. public static void main(String[] args) {
. try {
. // Create f1 object of the file to read data
. File f1 = new File("D:FileOperationExample.txt");
. Scanner dataReader = new Scanner(f1);
. while (dataReader.hasNextLine()) {
. String fileData = dataReader.nextLine();
. System.out.println(fileData);
. }
. dataReader.close();
. } catch (FileNotFoundException exception) {
. System.out.println("Unexcpected error occurred!");
. exception.printStackTrace();
. }
. }
. }
Delete a File:
. // Importing the File class
. import java.io.File;
. class DeleteFile {
. public static void main(String[] args) {
. File f0 = new File("D:FileOperationExample.txt");
. if (f0.delete()) {
. System.out.println(f0.getName()+ " file is deleted successfully.");
. } else {
. System.out.println("Unexpected error found in deletion of the file.");
. }
. }
. }
.
###Difference Between a Java Application and a Java Applet
Parameters Java Application Java Applet
Meaning and Basics A Java Application is a type of A Java Applet is a small program
program that can get independently that makes use of another
executed on a computer. application program so that we can
execute it.
Main() Method The execution of the Java application The Java applet initializes through
begins with the main() method. The the init(). It does not require the
usage of the main() is a prerequisite usage of any main() method.
here.
Execution It cannot run alone, but it requires JRE It cannot run independently but
for its execution. requires APIs for its execution (Ex.
APIs like Web API).
Installation One needs to install a Java application A Java applet does not require any
priorly and explicitly on a local prior installation.
computer.
Communication It is possible to establish It cannot really establish
among other Servers communication with the other servers. communication with the other
servers.
Read and Write The Java applications are capable of A Java applet cannot perform these
Operations performing the read and write applications on any local computer.
operations on various files present in a
local computer.
Restrictions These can easily access the file or data These cannot access the file or data
present in a computer system or device. available on any system or local
computers.
Security Java applications are pretty trusted, and Java applets are not very trusted.
thus, come with no security concerns. Thus, they require security.
Thread Life Cycle and Threading Basics:
1. Thread in Java:
A thread in Java is the direction or path that is taken while a program is being
executed. Generally, all the programs have at least one thread, known as the main
thread, that is provided by the JVM or Java Virtual Machine at the starting of the
program’s execution. At this point, when the main thread is provided, the main()
method is invoked by the main thread. A thread is an execution thread in a program.
Multiple threads of execution can be run concurrently by an application running on
the Java Virtual Machine. The priority of each thread varies. Higher priority threads
are executed before lower priority threads. Thread is critical in the program because it
enables multiple operations to take place within a single method. Each thread in the
program often has its own program counter, stack, and local variable.
2. Creating a Thread in Java
A thread in Java can be created in the following two ways:
Extending java.lang.Thread class: In this case, a thread is created by a new class that
extends the Thread class, creating an instance of that class. The run() method includes
the functionality that is supposed to be implemented by the Thread.
Implementing Runnable interface: This is the easy method to create a thread
among the two. In this case, a class is created to implement the runnable interface
and then the run() method.
Life cycle of a Thread in Java: The Life Cycle of a Thread in Java refers to the state
transformations of a thread that begins with its birth and ends with its death. When a
thread instance is generated and executed by calling the start() method of the Thread
class, the thread enters the runnable state. When the sleep() or wait() methods of the
Thread class are called, the thread enters a non-runnable mode. Thread returns from
non-runnable state to runnable state and starts statement execution. The thread dies
when it exits the run() process. In Java, these thread state transformations are referred
to as the Thread life cycle. There are basically 4 stages in the life cycle of a thread, as
given below:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
New State: As we use the Thread class to construct a thread entity, the thread is born and
is defined as being in the New state. That is, when a thread is created, it enters a new state,
but the start() method on the instance has not yet been invoked.
Runnable State: A thread in the runnable state is prepared to execute
the code. When a new thread's start() function is called, it enters a runnable state.
Running State: Running implies that the processor (CPU) has assigned a time slot to the
thread for execution. When a thread from the runnable state is chosen for execution by the
thread scheduler, it joins the running state. In the running state, the processor allots time to
the thread for execution and runs its run procedure. This is the state in which the thread
directly executes its operations. Only from the runnable state will a thread enter the
running state.
Blocked State: When the thread is alive, i.e., the thread class object persists, but it cannot
be selected for execution by the scheduler. It is now inactive.
Dead State: When a thread's run() function ends the execution of sentences, it
automatically dies or enters the dead state. That is, when a thread exits the run() process, it
is terminated or killed. When the stop() function is invoked, a thread will also go dead.
Java Thread Priorities: The number of services assigned to a given thread is
referred to as its priority. Any thread generated in the JVM is given a priority. The
priority scale runs from 1 to 10. 1 is known as the lowest priority. 5 is known as
standard priority. 10 represents the highest level of priority. The main thread's
priority is set to 5 by default, and each child thread will have the same priority as
its parent thread. We have the ability to adjust the priority of any thread, whether it
is the main thread or a user-defined thread. It is advised to adjust the priority using
the Thread class's constants, which are as follows:
1. Thread.MIN_PRIORITY;
2. Thread.NORM_PRIORITY;
3. Thread.MAX_PRIORITY;
Below is a program to understand the Thread Priority.
Multithreading in Java: In Java, multithreading is the method of running two or more
threads at the same time to maximize CPU utilization. As a result, it is often referred to
as Concurrency in Java. Each thread runs in parallel with the others. Since several
threads do not assign different memory areas, they conserve memory. Furthermore,
switching between threads takes less time. These generalized threads can be used in
high-server media applications to easily change or enhance the configuration of these
complex structures.
Java Inheritance (Subclass and Superclass): In Java, it is possible to inherit
attributes and methods from one class to another. We group the "inheritance concept"
into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass)
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the
Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}}
Serialization in Java:
Serialization in Java is a mechanism for writing an object's state into a byte stream. It is
mainly used in Hibernate, RMI, JPA, EJB, and JMS technologies.
The reverse operation of serialization is called deserialization, where the byte stream is
converted into an object. The serialization and deserialization process is platform-independent.
It means we can serialize an object on one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method of the ObjectOutputStream class,
and for deserialization, we call the readObject() method of the ObjectInputStream class.
Java's serialization feature transforms an object into a stream of bytes, making it easier to
store or send over a network. Many different technologies, including Hibernate, RMI (Remote
Method Invocation), JPA (Java Persistence API), EJB (Enterprise JavaBeans), and JMS (Java
Message Service), heavily utilize this method.
Advantages of Java Serialization:
It is mainly used to travel object's state on the network (that is known as marshalling).
1. Platform Independence: There are no compatibility problems when transferring
serialized objects between separate Java virtual machines (JVMs) running on different
platforms. Java Serialization is an effective technique for inter-system communication
because of its platform independence.
2. Network Communication: Java Serialization facilitates the transmission of object data
over a network. This process, known as marshalling, allows objects to be serialized into a
byte stream and sent across a network to be reconstructed on another machine. It is
crucial for applications involving distributed systems, such as client-server architectures
and web services.
3. Object Persistence: Serialization allows for indefinite storage of object state. Data can
be kept between program executions by using serialized objects, which can be saved to a
disc or a database and then retrieved..
Let's see the example given below:
. import java.io.Serializable;
. public class Student implements Serializable{
. int id;
. String name;
. public Student(int id, String name) {
. this.id = id;
. this.name = name;
. }
. }