100% found this document useful (1 vote)
1K views10 pages

Java File Handling and Operations Guide

The document discusses file handling in Java. It describes that a File is an abstract data type that represents a named location used to store related information. It discusses different file operations like creating, reading, writing and deleting files. It also describes streams in Java, including byte streams and character streams, and the most commonly used classes for each like FileInputStream, FileOutputStream, FileReader and FileWriter. Examples are provided for reading, writing and copying files using these stream classes. Serialization in Java is also summarized, which allows writing the state of an object to a byte-stream and reconstructing it, with examples of serializing and deserializing Person objects.

Uploaded by

ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views10 pages

Java File Handling and Operations Guide

The document discusses file handling in Java. It describes that a File is an abstract data type that represents a named location used to store related information. It discusses different file operations like creating, reading, writing and deleting files. It also describes streams in Java, including byte streams and character streams, and the most commonly used classes for each like FileInputStream, FileOutputStream, FileReader and FileWriter. Examples are provided for reading, writing and copying files using these stream classes. Serialization in Java is also summarized, which allows writing the state of an object to a byte-stream and reconstructing it, with examples of serializing and deserializing Person objects.

Uploaded by

ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • File Handling in Java
  • Examples of Stream Use
  • Serialization in Java

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.

Before understanding the File operations, it is required that we should have knowledge of
Stream and File methods. If you have knowledge about both of them, you can skip it.

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.

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream.
import [Link].*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

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. Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there are
many classes related to character streams but the most frequently used classes are, FileReader
and FileWriter.

import [Link].*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Example 1:
import [Link].*;

import [Link].*;

public class DataOutputStreamExample {

public static void main(String[] args) throws IOException {

OutputStream os = new FileOutputStream("D:\\[Link]");

DataOutputStream dos = new DataOutputStream(os);

int itemNo; String itemName, ch; double unitPrice;

Scanner in = new Scanner([Link]);

do

{ [Link]("Enter the item number, name and unit price:");

itemNo = [Link]();

itemName = [Link]();

unitPrice = [Link]();

[Link](itemNo);

[Link](itemName);

[Link](unitPrice);

[Link]("Continue(y/n)?");

ch = [Link]();

}while([Link]("yes"));

[Link]();

}
Example 2:
import [Link].*;

public class DataInputStreamExample {

public static void main(String[] args) throws IOException {

InputStream is = new FileInputStream("D:\\[Link]");

DataInputStream dis = new DataInputStream(is);

int itemNo; String itemName, ch; double unitPrice;

while([Link]() > 0 ){

itemNo = [Link]();

itemName = [Link]();

unitPrice = [Link]();

[Link](itemNo + "\t" + itemName + "\t" + unitPrice);

[Link]();

Example 3:
import [Link];

import [Link];

import [Link];

class ReadFromFile {

public static void main(String[] args) {

try {

// Create f1 object of the file to read data


File f1 = new File("D:[Link]");

Scanner dataReader = new Scanner(f1);

while ([Link]()) {

String fileData = [Link]();

[Link](fileData);

[Link]();

} catch (FileNotFoundException exception) {

[Link]("Unexcpected error occurred!");

[Link]();

Serialization
Serialization in Java is a mechanism of writing the state of an object 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 byte-stream is converted


into an object. The serialization and deserialization process is platform-independent, it means
you can serialize an object in a platform and deserialize in different platform.

For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization

It is mainly used to travel object's state on the network (which is known as marshaling).
Serializable is a marker interface (has no data member and method). It is used to "mark"
Java classes so that the objects of these classes may get a certain capability. The Cloneable
and Remote are also marker interfaces.

It must be implemented by the class whose object you want to persist.

The String class and all the wrapper classes implement the [Link] interface by
default.

Let's see the example given below:


Filename: [Link]

import [Link];

public class Person implements Serializable {

private static final long serialVersionUID = 1L;


private String name;
private int age;
private String gender;

Person() {
};

Person(String name, int age, String gender) {


[Link] = name;
[Link] = age;
[Link] = gender;
}

@Override
public String toString() {
return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
}
}

Filename: [Link]
import [Link].*;

public class WriterReader {

public static void main(String[] args) {

Person p1 = new Person("John", 30, "Male");


Person p2 = new Person("Rachel", 25, "Female");

try {
FileOutputStream f = new FileOutputStream(new
File("[Link]"));
ObjectOutputStream o = new ObjectOutputStream(f);

// Write objects to file


[Link](p1);
[Link](p2);

[Link]();
[Link]();

FileInputStream fi = new FileInputStream(new


File("[Link]"));
ObjectInputStream oi = new ObjectInputStream(fi);

// Read objects
Person pr1 = (Person) [Link]();
Person pr2 = (Person) [Link]();

[Link](“ ” +pr1);
[Link]([Link]());

[Link]();
[Link]();

} catch (FileNotFoundException e) {
[Link]("File not found");
} catch (IOException e) {
[Link]("Error initializing stream");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
[Link]();
}

Java Serialization with Inheritance (IS-A Relationship)

If a class implements serializable then all its sub classes will also be serializable. Let's see the
example given below:

import [Link];
class Person implements Serializable{
int id;
String name;
Person(int id, String name) {
[Link] = id;
[Link] = name;
}
}
class Student extends Person{
String course;
int fee;
public Student(int id, String name, String course, int fee) {
super(id,name);
[Link]=course;
[Link]=fee;
}
}

Common questions

Powered by AI

To handle a FileNotFoundException in Java, especially when reading from a file, you encapsulate your file reading code within a try-catch block. Inside the catch block, print an error message to the console, optionally followed by stack trace printing to help identify the calling method and line where the exception occurred .

ObjectInputStream and ObjectOutputStream are tailored for serializing and deserializing objects rather than just byte or character data. They handle object metadata, keeping class type and hierarchy intact during serialization, while traditional file streams do not. This makes object streams superior for transmitting complex object graphs over file streams, which are limited to primitive data handling .

FileInputStream is used for reading raw byte data, useful when dealing with binary files, whereas FileReader is designed for reading streams of characters, ideal for text files that leverage character encoding . FileInputStream is suitable for reading data like images or executable files, while FileReader would be the better choice for reading or processing textual data in a character form .

Classes must implement the Serializable interface to be eligible for deserialization because Java's serialization mechanism relies on this "marker" interface to identify classes whose objects can be serialized or deserialized. Marker interfaces, like Serializable, do not contain methods but serve as indicators to the JVM to grant certain capabilities to classes, such as participating in the serialization process .

Implementing the Serializable interface in Java enables an object's state to be converted into a byte-stream, allowing it to be easily transmitted over networks (a process known as marshaling). This functionality is crucial for applications using RMI, Hibernate, or JMS, as it facilitates seamless object state management and exchange across distributed systems .

Serialization ensures object integrity by converting the state into a byte-stream that maintains state properties entirely until deserialization. Security during serialization is primarily the developer's responsibility, who should validate and transform data to prevent arbitrary code execution during deserialization. Additionally, using serialPersistentFields or readObject methods can help with controlling how classes are serialized and deserialized securely .

Java serialization converts an object's state into a byte-stream, which can then be restored into an object on any platform through deserialization. This process is platform-independent due to the uniform handling of data types in serialized forms supported by Java's serialization API, allowing objects to be serialized on one platform and deserialized on another .

To use Scanner for reading data from a file in Java, first, create a File object linked to the file path. Pass this File object to Scanner's constructor to read its data. Use a try-catch block to catch FileNotFoundException and possibly IOException to handle situations where the file path may be incorrect or inaccessible, ensuring the application can handle errors without crashing .

Byte streams handle 8-bit byte data and are used for input and output of bytes, as seen in the frequent use of classes like FileInputStream and FileOutputStream . Character streams, on the other hand, manage 16-bit Unicode character data, leveraging classes such as FileReader and FileWriter for handling characters .

The try-with-resources statement in Java simplifies resource management by automatically closing resources that implement the AutoCloseable interface, such as streams and readers, at the end of the statement's execution. This prevents resource leaks and eliminates the need for explicit close calls within finally blocks, enhancing code readability and reliability .

File Handling in Java 
In Java, (https://www.javatpoint.com/java-tutorial) a File is an abstract data type. A named location
import java.io.*; 
public class CopyFile { 
 
   public static void main(String args[]) throws IOException {   
      FileInp
}finally { 
         if (in != null) { 
            in.close(); 
         } 
         if (out != null) { 
            o
Example 1: 
import java.io.*;     
import java.util.*; 
public class DataOutputStreamExample {   
  public static void main(S
Example 2: 
import java.io.*;     
public class DataInputStreamExample {   
  public static void main(String[] args) throws I
File f1 = new File("D:FileOperationExample.txt");     
            Scanner dataReader = new Scanner(f1);
Serializable is a marker interface (has no data member and method). It is used to "mark" 
Java classes so that the object
Filename: Person.java 
 
import java.io.Serializable; 
 
public class Person implements Serializable { 
 
 
private static fi
f.close(); 
 
 
 
 
FileInputStream fi = new FileInputStream(new 
File("myObjects.txt")); 
 
 
 
ObjectInputStream oi =
}   
class Student extends Person{   
 String course;   
 int fee;   
 public Student(int id, String name, String course, int

You might also like