Introduction
Java I/O (Input/Output) ka use hum tab karte hain jab hume data ko:
- File mein read/write karna ho
- Network ya memory se data lena/dena ho
- Objects ko save ya retrieve karna ho (Serialization)
Java I/O ke major parts hain:
- Byte Streams – Binary data ke liye
- Character Streams – Text data ke liye
- File Handling – Files ko access karne ke liye
- Serialization/Deserialization – Object save/load
- transient keyword – Object ke kuch parts skip karne ke liye
- NIO (New I/O) – Efficient file handling
1. Byte Streams – InputStream & OutputStream
- InputStream: Binary data read karne ke liye
- OutputStream: Binary data write karne ke liye
Example – Reading file using FileInputStream
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}
fis.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Hello Java Byte Stream!
(Assuming example.txt
file mein ye hi content likha hai)
Example – Writing file using FileOutputStream
import java.io.FileOutputStream;
public class WriteFile {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("example.txt");
String s = "Hello Java Byte Stream!";
fos.write(s.getBytes());
fos.close();
System.out.println("File written successfully.");
} catch (Exception e) {
System.out.println(e);
}
}
}
Output on Console:
File written successfully.
File Content (example.txt):
Hello Java Byte Stream!
2. Character Streams – Reader & Writer
Yeh text files ke liye use hote hain (encoding-aware).
- Reader: Characters read karta hai
- Writer: Characters write karta hai
Example – Reading using FileReader
import java.io.FileReader;
public class ReadChar {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("example.txt");
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
fr.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Hello from Java Writer!
(Assuming example.txt mein ye text hai)
Example – Writing using FileWriter
import java.io.FileWriter;
public class WriteChar {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("example.txt");
fw.write("Hello from Java Writer!");
fw.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output on Console:
(No console output, but file is updated)
File Content:
Hello from Java Writer!
3. File Handling (File, FileReader, FileWriter)
File
class file ya directory ko represent karta hai. Aap check kar sakte ho:
- File exists?
- File create karna
- File delete karna
- Properties check karna (name, path, size)
Example – File creation & info
import java.io.File;
public class FileExample {
public static void main(String[] args) {
try {
File f = new File("test.txt");
if (f.createNewFile()) {
System.out.println("File created: " + f.getName());
} else {
System.out.println("File already exists.");
}
System.out.println("Path: " + f.getAbsolutePath());
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
File created: test.txt
Path: C:\Users\...\test.txt
(If file already exists:)
File already exists.
Path: C:\Users\...\test.txt
4. Serialization & Deserialization
Jab hume objects ko file mein save karna ho ya network se bhejna ho, tab use karte hain.
Serializable
Interface
- Marker interface – koi method nahi
- Bas batata hai JVM ko ki is object ko serialize kiya ja sakta hai
Example – Serialize Object
import java.io.*;
class Student implements Serializable {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class SerializeDemo {
public static void main(String[] args) {
try {
Student s = new Student(101, "Rahul");
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
oos.close();
fos.close();
System.out.println("Object saved");
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Object saved
File Created:
student.ser
(Binary file, human-readable nahi hoga)
Example – Deserialize Object
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s = (Student) ois.readObject();
System.out.println(s.id + " " + s.name);
ois.close();
fis.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
101 Rahul
5. transient
Keyword
Agar kisi field ko serialize nahi karna chahte ho to use transient declare karo.
Example:
class Student implements Serializable {
int id;
transient String password; // will not be saved
public Student(int id, String password) {
this.id = id;
this.password = password;
}
}
Deserialization ke baad password
null ho jayega.
During Deserialization Output:
101 null
(Password will not be restored)
6. Java NIO (New I/O)
NIO Java 7 mein aaya, aur ye faster and buffer-based file handling provide karta hai.
Important NIO Classes:
Path
: File path ko represent karta haiFiles
: File create, delete, read/writeBuffers
: Data hold karne ke liyeChannels
: File ka data transfer
Example – Reading file using NIO
import java.nio.file.*;
import java.util.List;
public class NIORead {
public static void main(String[] args) throws Exception {
Path path = Paths.get("example.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
}
}
Output:
Hello from Java Writer!
Example – Writing file using NIO
import java.nio.file.*;
import java.util.*;
public class NIOWrite {
public static void main(String[] args) throws Exception {
Path path = Paths.get("nio_output.txt");
List<String> lines = Arrays.asList("Java", "NIO", "is", "Fast");
Files.write(path, lines);
System.out.println("Written using NIO");
}
}
Console Output:
Written using NIO
File Content (nio_output.txt):
Java
NIO
is
Fast
Conclusion
Java I/O and File Handling ek important topic hai jiska use real projects mein har jagah hota hai – chahe wo file read karni ho, object save karna ho, ya binary data write karna ho.
Aap in classes ko ache se samajhkar file systems, network apps, and data processing projects build kar sakte ho isse tumhare file handling concept aur bhi concrete ho jayega.
Comments