Unit 5 -syllabus
Text and binary I/O,Binary I./O classes, Object I/O, Random Access files, multithreading in java: thread life cycle and methods, Runnable interface, Thread synchronisation, exception handling with try catch-Finally, Collections in java, Introduction to java beans and network program
1. Text and Binary I/O in Java
Text I/O
Deals with reading and writing character data.
Uses classes like FileReader, BufferedReader, FileWriter, and PrintWriter.
Example:
import java.io.*;
public class TextIOExample {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, Java!");
writer.close();
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
System.out.println(reader.readLine());
reader.close();
}
}
Binary I/O
Deals with reading and writing binary data such as images, audio, and serialized objects.
Uses FileInputStream and FileOutputStream.
Example:
import java.io.*;
public class BinaryIOExample {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("binary.dat");
fos.write(65);
fos.close();
FileInputStream fis = new FileInputStream("binary.dat");
System.out.println(fis.read());
fis.close();
}
}
2. Binary I/O Classes in Java
Key Classes:
FileInputStream / FileOutputStream
DataInputStream / DataOutputStream
ObjectInputStream / ObjectOutputStream
RandomAccessFile
3. Object I/O in Java
Serialization is used to store object states into a file.
ObjectOutputStream and ObjectInputStream are used.
Example:
import java.io.*;
class Student implements Serializable {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class ObjectIOExample {
public static void main(String[] args) throws Exception {
Student s1 = new Student("Alice", 20);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.dat"));
oos.writeObject(s1);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.dat"));
Student s2 = (Student) ois.readObject();
System.out.println(s2.name + " " + s2.age);
ois.close();
}
}
4. Random Access Files
Allows reading and writing at specific positions in a file.
Uses RandomAccessFile.
Example:
import java.io.*;
public class RandomAccessExample {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("test.dat", "rw");
raf.writeInt(100);
raf.seek(0);
System.out.println(raf.readInt());
raf.close();
}
}
5. Multithreading in Java
Thread Life Cycle
1. New – Created using Thread or Runnable.
2. Runnable – Ready to run when CPU is available.
3. Blocked/Waiting – Waiting for a resource or signal.
4. Running – Executing.
5. Terminated – Thread has finished execution.
Thread Methods
start(), run(), sleep(), yield(), join(), interrupt()
6. Runnable Interface
Alternative way to create a thread.
Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running.");
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
7. Thread Synchronization
Ensures that multiple threads do not interfere with shared resources.
synchronized keyword is used.
Example:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class SyncExample {
public static void main(String[] args) {
Counter c = new Counter();
Thread t1 = new Thread(() -> { for(int i=0; i<1000; i++) c.increment(); });
Thread t2 = new Thread(() -> { for(int i=0; i<1000; i++) c.increment(); });
t1.start();
t2.start();
}
}
8. Exception Handling in Java
Using try-catch-finally
try: Code that may throw an exception.
catch: Handles the exception.
finally: Executes regardless of an exception.
Example:
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution completed.");
}
}
}
9. Collections in Java
Types of Collections
List: ArrayList, LinkedList
Set: HashSet, TreeSet
Queue: PriorityQueue, Deque
Map: HashMap, TreeMap
Example:
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
System.out.println(list);
}
}
10. Introduction to JavaBeans
JavaBeans are reusable software components.
Rules:
Should be public and have a no-argument constructor.
Private properties with public getter and setter methods.
Example:
public class PersonBean implements java.io.Serializable {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
11. Network Programming in Java
Socket Programming
Uses Socket and ServerSocket.
Client:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello Server");
socket.close();
}
}
Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
serverSocket.close();
}
}