Reading and writing Files:-
File handling is an essential aspect of programming, and Java provides numerous libraries for
handling files. In this article, we will discuss how to read and write files using Java libraries.
Java provides two core libraries for handling files:
1. [Link] package
2. [Link] package
The [Link] package is used for file handling in Java. It provides various classes for handling
files, such as File, FileReader, FileWriter, FileInputStream, and FileOutputStream.
The [Link] package is the newer file handling library, introduced in Java 1.4. It provides
better performance and scalability than the [Link] package. It provides classes like
FileChannel, ByteBuffer, and Charset.
Reading from a File
To read data from a file, you need to follow the following steps:
1. Create a File object that represents the file you want to read.
2. Create a FileReader object that reads data from the file.
3. Use the read() method of the FileReader object to read data from the file.
4. Close the FileReader object using the close() method.
import [Link];
import [Link];
import [Link];
public class ReadFromFile
{
public static void main(String[] args) throws IOException
{
File file = new File("[Link]");
FileReader fr = new FileReader(file);
int ch;
while ((ch=[Link]()) != -1)
{
[Link]((char)ch);
}
[Link]();
}
}
Writing to a File
To write data to a file, you need to follow the following steps:
1. Create a File object that represents the file you want to write to.
2. Create a FileWriter object that writes data to the file.
3. Use the write() method of the FileWriter object to write data to the file.
4. Close the FileWriter object using the close() method.
Here is an example:
import [Link];
import [Link];
import [Link];
public class WriteToFile
{
public static void main(String[] args) throws IOException
{
File file = new File("[Link]");
FileWriter fw = new FileWriter(file);
[Link]("Hello World!");
[Link]();
}
}
Java Console class
The [Link] class in Java provides methods to interact with the character-based
console device, if one exists, associated with the current Java Virtual Machine. This class was
introduced in Java SE 6 and offers a more convenient way to handle console input and output
compared to directly using [Link] and [Link] for certain scenarios, especially for
sensitive data like passwords.
Key Features and Usage:
Obtaining a Console Object: The Console class does not have a public constructor. Instead,
you obtain an instance by calling the static [Link]() method. If a console is not
available (e.g., when running in an IDE or a non-interactive
environment), [Link]() will return null.
Reading Input:
readLine(): Reads a single line of text from the console.
readPassword(): Reads a password from the console without echoing the characters typed by
the user, returning a char[]. This is crucial for security.
Writing Output:
printf(): Provides formatted output to the console, similar to [Link]().
writer(): Returns a PrintWriter object associated with the console for more general output
operations.
Program:
import [Link];
public class ConsoleExample
{
public static void main(String[] args)
{
Console console = [Link]();
if (console != null)
{
String username = [Link]("Enter username: ");
char[] password = [Link]("Enter password: ");
[Link]("Hello, %s!%n", username);
[Link](password, ' *');
}
else
{
[Link]("No console available.");
}
}
}
Important Considerations:
The Console class is designed for command-line applications and will return null if executed
within many Integrated Development Environments (IDEs) like Eclipse or IntelliJ, as they
often don't provide a true console environment for [Link].
When handling passwords, always use readPassword() and clear the char[] array after use to
prevent sensitive data from lingering in memory.
Serialization
In Java, serialization plays a very important role it's something that we use a lot in our real
life, even if we do not always notice it. Serialization helps us to save the current state of an
object so that we can use it further and share complex data between different systems.
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object's data as well as information about the object's type
and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized
that is, the type information and bytes that represent the object and its data can be used to
recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
Serialization is a mechanism of converting the state of an object into a byte stream.
Important Points of Serialisation:
Platform-Independent: In Java, the serialization is a platform-independent process. It
means that if we serialize an object using a byte stream on one platform can be easily
deserialized on different platforms.
Serializable Interface: If we want to make a class serializable, then it must implement
the Serializable interface. This interface does not contain any methods or variables (
marker interface), but it gives a signal that the class is ready for serialization.
Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo
program instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named [Link] is created. The program does
not generate any output, but study the code and try to determine what the program is doing.
Program:
import [Link].*;
class Employee implements Serializable
{
String name;
int num;
Employee(String name,int num)
{
[Link]=name;
[Link]=num;
}
}
class SerializationDemo
{
public static void main(String arg[])
{
Employee e1=new Employee("saikiran",125);
try
{
FileOutputStream fout=new FileOutputStream("[Link]");
ObjectOutputStream out=new ObjectOutputStream(fout);
[Link](e1);
[Link]();
[Link]();
[Link]("success");
}
catch(Exception e)
{
[Link]();
}
}
}
Deserializing an Object
The following DeserializeDemo program deserializes the Employee object created in the
earlier program. Study the program and try to determine its output −
Example for Deserializing an Object
import [Link].*;
class Employee implements Serializable
{
String name;
int num;
Employee(String name,int num)
{
[Link]=name;
[Link]=num;
}
}
class SerializationDemo2
{
public static void main(String arg[])
{
try
{
FileInputStream fin=new FileInputStream("[Link]");
ObjectInputStream in=new ObjectInputStream(fin);
Employee e1=(Employee)[Link]();
[Link]();
[Link]();
[Link]([Link]+" "+[Link]);
}
catch(Exception e)
{
[Link]();
}
}}