KEMBAR78
? File Handling & I - O Streams in Java | PDF | Spring Framework | Computer File
0% found this document useful (0 votes)
3 views22 pages

? File Handling & I - O Streams in Java

Uploaded by

Sakshi G
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
0% found this document useful (0 votes)
3 views22 pages

? File Handling & I - O Streams in Java

Uploaded by

Sakshi G
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
You are on page 1/ 22

📒 File Handling & I/O Streams in Java

🔹 1. Introduction
●​ File handling allows programs to store data permanently on disk.​

●​ Java provides the java.io package and newer java.nio for file operations.​

●​ Streams are the abstraction used for input/output (I/O).​

🔹 2. Types of Streams
Streams = sequence of data.

1.​ Byte Streams (handle raw binary data)​

○​ Classes: FileInputStream, FileOutputStream​

○​ Useful for images, videos, audio files, etc.​

2.​ Character Streams (handle text data, Unicode-aware)​

○​ Classes: FileReader, FileWriter​

○​ Useful for .txt files, text-based data.​

🔹 3. Important Classes in java.io


1.​ File Class​

○​ Represents file/directory path.​

Constructors:​

File f1 = new File("test.txt");
File f2 = new File("C:\\Users\\sakshi\\mydata");

○​
○​ Common methods:​

■​ exists() → check if file exists​


■​ createNewFile() → create file​

■​ delete() → delete file​

■​ isDirectory(), isFile()​

■​ length() → file size in bytes​

■​ list() → list of files in a directory​

2.​ FileInputStream / FileOutputStream (Byte Stream)​

Reading bytes:​

FileInputStream fin = new FileInputStream("test.txt");
int i;
while((i = fin.read()) != -1) {
System.out.print((char)i);
}
fin.close();

○​

Writing bytes:​

FileOutputStream fout = new FileOutputStream("test.txt");
fout.write(65); // writes 'A'
fout.close();

○​
3.​ FileReader / FileWriter (Character Stream)​

Reading chars:​

FileReader fr = new FileReader("test.txt");
int i;
while((i = fr.read()) != -1) {
System.out.print((char)i);
}
fr.close();

○​

Writing chars:​

FileWriter fw = new FileWriter("test.txt");
fw.write("Hello Sakshi");
fw.close();

○​
4.​ Buffered Streams (improve performance by reducing disk access)​
○​ BufferedReader, BufferedWriter for characters​

○​ BufferedInputStream, BufferedOutputStream for bytes​


Example:​

BufferedReader br = new BufferedReader(new FileReader("test.txt"));


String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();

5.​

PrintWriter (easy writing of formatted text)​



PrintWriter pw = new PrintWriter("output.txt");
pw.println("Hello World");
pw.close();

6.​

🔹 4. Serialization in Java (special topic under file handling)


●​ Serialization: process of saving object’s state to a file (binary form).​

●​ Deserialization: restoring object back from file.​

●​ Classes: ObjectOutputStream, ObjectInputStream.​

Example:​

class Student implements Serializable {
int id; String name;
Student(int id, String name) { this.id = id; this.name = name; }
}

// Serialization
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.ser"));
oos.writeObject(new Student(101, "Sakshi"));
oos.close();

// Deserialization
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));
Student s = (Student)ois.readObject();
System.out.println(s.id + " " + s.name);
ois.close();

●​
🔹 5. Exception Handling in File I/O
●​ File handling involves checked exceptions (IOException,
FileNotFoundException).​

●​ Must be handled with try-catch or declared with throws.​

Example:​

try(FileReader fr = new FileReader("test.txt")) { // try-with-resources
int i;
while((i = fr.read()) != -1) System.out.print((char)i);
} catch(IOException e) {
e.printStackTrace();
}

●​

🔹 6. Common MCQ Points


●​ File class → only represents file/directory, doesn’t read/write contents.​

●​ Byte stream vs Character stream → byte for binary, char for text.​

●​ BufferedReader → has readLine() method, FileReader doesn’t.​

●​ Serialization → class must implement Serializable.​

●​ try-with-resources → introduced in Java 7, auto-closes streams.​

Perfect 😎 Let’s move on to the next topic →

📒 Java Collection Framework


🔹 1. Introduction
●​ A Collection = an object that groups multiple elements into a single unit (like
containers).​

●​ Java provides the Collection Framework (java.util package) → ready-made


classes & interfaces for data structures (lists, sets, maps, queues).​

●​ Advantages:​

○​ Reusable, efficient, well-tested data structures​


○​ Reduces programming effort​

○​ Provides algorithms (sorting, searching, etc.)​

🔹 2. Core Interfaces of Collection Framework


1.​ Collection (root interface)​

○​ Extended by List, Set, and Queue.​

○​ Defines basic methods: add(), remove(), size(), iterator(), etc.​

2.​ List Interface​

○​ Ordered collection, allows duplicates.​

○​ Classes: ArrayList, LinkedList, Vector, Stack.​

3.​ Set Interface​

○​ Unordered collection, no duplicates.​

○​ Classes: HashSet, LinkedHashSet, TreeSet.​

4.​ Queue Interface​

○​ Elements processed in FIFO order.​

○​ Classes: PriorityQueue, ArrayDeque.​

5.​ Map Interface (not child of Collection, but part of framework)​

○​ Stores data in key-value pairs.​

○​ Classes: HashMap, LinkedHashMap, TreeMap, Hashtable.​

🔹 3. Important Classes
ArrayList

●​ Resizable array (dynamic).​

●​ Allows duplicates, maintains insertion order.​

Example:​

ArrayList<String> list = new ArrayList<>();
list.add("A");

list.add("B");

list.add("A"); // duplicates allowed

System.out.println(list); // [A, B, A]

●​

LinkedList

●​ Doubly linked list implementation.​

●​ Faster insert/delete than ArrayList, slower for random access.​

Example:​

LinkedList<Integer> ll = new LinkedList<>();

ll.add(10); ll.addFirst(5); ll.addLast(20);

System.out.println(ll); // [5, 10, 20]

●​

HashSet

●​ Implements Set, no duplicates, unordered.​

●​ Uses hashing.​

Example:​

HashSet<Integer> hs = new HashSet<>();

hs.add(10); hs.add(20); hs.add(10);

System.out.println(hs); // [20, 10] (order not guaranteed)

●​

LinkedHashSet

●​ Maintains insertion order + no duplicates.​

TreeSet

●​ Sorted set (elements in ascending order).​

Example:​

TreeSet<Integer> ts = new TreeSet<>();

ts.add(30); ts.add(10); ts.add(20);


System.out.println(ts); // [10, 20, 30]

●​

HashMap

●​ Stores key-value pairs, keys are unique, values can duplicate.​

●​ Unordered, fast (uses hashing).​

Example:​

HashMap<Integer, String> map = new HashMap<>();

map.put(1, "A");

map.put(2, "B");

map.put(1, "C"); // overwrites value for key=1

System.out.println(map); // {1=C, 2=B}

●​

LinkedHashMap

●​ Maintains insertion order.​

TreeMap

●​ Sorted map (keys in ascending order).​

Hashtable

●​ Legacy class, synchronized (thread-safe).​

●​ Similar to HashMap but slower.​

🔹 4. Iterating Collections
Iterator:​

Iterator<String> it = list.iterator();

while(it.hasNext()) {

System.out.println(it.next());

●​
For-each loop:​

for(String s : list) {

System.out.println(s);

●​

🔹 5. Utility Class: Collections


●​ Provides static methods like:​

○​ Collections.sort(list)​

○​ Collections.reverse(list)​

○​ Collections.max(list)​

○​ Collections.min(list)​

🔹 6. Common MCQ Points


●​ ArrayList → dynamic array, allows duplicates.​

●​ HashSet → no duplicates, order not guaranteed.​

●​ LinkedHashSet → maintains insertion order.​

●​ TreeSet → sorted, no duplicates.​

●​ HashMap → key-value, null key allowed (only one).​

●​ Hashtable → legacy, no null key/value allowed.​

●​ TreeMap → sorted map, null key not allowed.​

Perfect 🚀 Let’s lock in JDBC basics (MCQ-oriented, exam-friendly).

📒 JDBC (Java Database Connectivity)


🔹 1. Introduction
●​ JDBC = API for connecting Java applications to databases.​

●​ Part of java.sql package.​

●​ Works as a bridge between Java code & database.​

🔹 2. JDBC Architecture
1.​ JDBC API → Java code written by programmer.​

2.​ JDBC Driver Manager → Manages drivers.​

3.​ JDBC Driver → Translates Java calls into DB-specific calls.​

4.​ Database → Backend (MySQL, Oracle, etc.).​

🔹 3. Steps to Connect JDBC


Load Driver Class​

Class.forName("com.mysql.cj.jdbc.Driver");

1.​

Establish Connection​

Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/dbname", "user", "password");

2.​

Create Statement​

Statement stmt = con.createStatement();

3.​

Execute Query​

ResultSet rs = stmt.executeQuery("SELECT * FROM student");

4.​

Process Results​

while(rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}

5.​
Close Connection​

con.close();

6.​

🔹 4. Types of JDBC Drivers


1.​ Type 1: JDBC-ODBC Bridge Driver​

○​ Uses ODBC internally.​

○​ Slow, platform-dependent.​

○​ Obsolete (removed in Java 8).​

2.​ Type 2: Native API Driver​

○​ Uses DB’s native libraries.​

○​ Faster than Type 1, but platform-dependent.​

3.​ Type 3: Network Protocol Driver​

○​ Uses middleware server.​

○​ DB-independent, flexible.​

4.​ Type 4: Thin Driver (Pure Java)​

○​ Directly converts JDBC calls into DB protocol.​

○​ Platform-independent, widely used.​

🔹 5. Key Interfaces
●​ Driver → For DB drivers.​

●​ Connection → Represents a connection with DB.​

●​ Statement → Executes SQL queries.​

●​ PreparedStatement → Precompiled SQL, safer & faster.​

●​ CallableStatement → Calls stored procedures.​

●​ ResultSet → Stores results of query.​


🔹 6. Important Points for MCQ
●​ Default package for JDBC → java.sql.​

●​ Which driver is best? → Type 4 (pure Java).​

●​ JDBC-ODBC bridge (Type 1) is removed in JDK 8.​

●​ executeQuery() → used for SELECT (returns ResultSet).​

●​ executeUpdate() → for INSERT, UPDATE, DELETE (returns int).​

●​ execute() → can run any SQL (returns boolean).​

●​ ResultSet methods:​

○​ rs.next() → moves cursor forward.​

○​ rs.getInt(), rs.getString(), rs.getDate() → fetch data.​

●​ SQL Injection risk reduced by PreparedStatement.​

●​ Transactions:​

○​ con.setAutoCommit(false);​

○​ con.commit(); / con.rollback();​

Perfect🔥 Let’s go step by step with Servlets & JSP basics (MCQ-level, lightweight coding,
enough to crack questions).

📒 Servlets & JSP (Basics)


🔹 1. Servlets (Java Server Components)
What is a Servlet?

●​ Java program that runs on a server and handles client requests (mostly HTTP).​

●​ Part of Java EE (Enterprise Edition).​

●​ Extends capabilities of a web server.​


Servlet Lifecycle (very MCQ-important 🚨)
1.​ Load & Instantiate → Servlet class loaded.​

2.​ init() → called once when servlet is first created.​

3.​ service() → called for every request.​

○​ Handles doGet(), doPost() methods.​

4.​ destroy() → called once when servlet is unloaded.​

Common Methods in HttpServlet

●​ doGet(HttpServletRequest req, HttpServletResponse res)​

●​ doPost(HttpServletRequest req, HttpServletResponse res)​

●​ getParameter("name") → fetch form data.​

●​ setContentType("text/html") → set response type.​

Advantages of Servlets

●​ Portable (Java-based).​

●​ Better than CGI (Common Gateway Interface).​

●​ Efficient (multi-threaded).​

MCQ Pointers for Servlets

●​ Servlet is in javax.servlet and javax.servlet.http packages.​

●​ Default constructor is called → then init().​

●​ service() calls doGet() / doPost().​

●​ Lifecycle managed by Servlet Container (like Tomcat).​

●​ One servlet object → multiple requests handled via threads.​


🔹 2. JSP (Java Server Pages)
What is JSP?

●​ Java technology for developing dynamic web pages.​

●​ Allows mixing HTML + Java code using special tags.​

●​ Easier than writing full servlets for UI.​

JSP Lifecycle

1.​ Translation → JSP converted to Servlet.​

2.​ Compilation → Servlet compiled to bytecode.​

3.​ Loading & Initialization → same as servlet init.​

4.​ Execution → request handled by _jspService().​

5.​ Destroy → jspDestroy().​

JSP Scripting Elements

●​ Declarations <%! %> → declare variables/methods.​

●​ Scriptlets <% %> → Java code inside JSP.​

●​ Expressions <%= %> → output directly.​

Example:

<%! int counter = 0; %>


<% counter++; %>
<p>Counter: <%= counter %></p>

JSP Directives

●​ Page Directive: <%@ page language="java" contentType="text/html"


%>​

●​ Include Directive: <%@ include file="header.jsp" %>​

●​ Taglib Directive: <%@ taglib uri="..." prefix="..." %>​


JSP Implicit Objects (super important MCQ 🚨)
Automatically available in JSP:

●​ request → HttpServletRequest​

●​ response → HttpServletResponse​

●​ session → HttpSession​

●​ application → ServletContext​

●​ out → JspWriter​

●​ config, pageContext, page, exception​

JSP vs Servlet (Exam Trap Question ⚡)


●​ Servlet: All Java, more control, harder for UI.​

●​ JSP: HTML + Java, easier for UI, automatically converted into a servlet.​

MCQ Quick Facts

●​ JSP compiled into servlet once (first request).​

●​ _jspService() method generated automatically.​

●​ JSP is better for presentation layer, Servlet for business logic.​

●​ out.print() in JSP is same as System.out.println() in servlet response.​

●​ Lifecycle methods: jspInit(), _jspService(), jspDestroy().​

Got it👍 let’s knock out the Spring Framework basics (optional, high-level only) — just
what you’d need for MCQs or conceptual questions, no deep-dive coding.

📒 Spring Framework Basics (Optional)


🔹 1. What is Spring?
●​ Lightweight, open-source Java framework.​

●​ Used to build enterprise applications.​

●​ Provides dependency injection (DI) and aspect-oriented programming (AOP).​

●​ Makes Java EE development easier.​

🔹 2. Core Concepts
a) Inversion of Control (IoC)

●​ Instead of the programmer creating objects, the Spring Container manages object
creation and dependencies.​

●​ Done via Dependency Injection (DI).​

Example:

●​ Without DI → Car car = new Car(new Engine());​

●​ With DI → Spring injects Engine into Car automatically.​

b) Dependency Injection (DI)

●​ Two main types:​

○​ Constructor Injection​

○​ Setter Injection​

c) Spring Modules

1.​ Core Container (BeanFactory, ApplicationContext)​

2.​ Spring MVC (for web apps, follows MVC pattern)​

3.​ Spring AOP (cross-cutting concerns like logging, security)​

4.​ Spring JDBC & ORM (database handling)​

5.​ Spring Boot (simplifies Spring setup, auto-config).​


🔹 3. Spring MVC (Basics Only)
●​ MVC = Model, View, Controller.​

●​ Used for web applications.​

●​ Workflow:​

1.​ User sends request → DispatcherServlet.​

2.​ DispatcherServlet → Controller.​

3.​ Controller → Service → DAO → Database.​

4.​ Result returned → JSP/HTML view.​

🔹 4. Spring Boot (Shortcut to Spring)


●​ Extension of Spring framework.​

●​ Provides auto-configuration.​

●​ Embedded servers (Tomcat, Jetty) → no need for manual setup.​

●​ Uses annotations heavily (@SpringBootApplication, @RestController).​

🔹 5. Quick MCQ-Oriented Facts


●​ Spring is based on Dependency Injection (DI) and Inversion of Control (IoC).​

●​ Core container provides → BeanFactory & ApplicationContext.​

●​ Spring MVC follows Front Controller pattern using DispatcherServlet.​

●​ Spring Boot simplifies Spring setup.​

●​ Common annotations:​

○​ @Component, @Service, @Repository, @Controller.​

○​ @Autowired → dependency injection.​

●​ AOP = aspect-oriented programming (logging, transactions).​

📒 File Handling in C++ (Detailed Notes)


🔹 1. Introduction
●​ File Handling = storing data permanently on secondary storage (hard disk).​

●​ In C++, handled through File Streams in <fstream> library.​

🔹 2. File Stream Classes


C++ provides three main classes in <fstream>:

1.​ ifstream → input file stream (read from file).​

2.​ ofstream → output file stream (write to file).​

3.​ fstream → input + output file stream (read + write).​

👉 All are derived from base class ios → and use flags for modes.
🔹 3. Opening a File
Syntax
ifstream in("input.txt"); // read mode
ofstream out("output.txt"); // write mode
fstream file("data.txt", ios::in | ios::out);

Modes (from ios class)

●​ ios::in → read​

●​ ios::out → write​

●​ ios::app → append at end​

●​ ios::ate → open and move pointer at end​

●​ ios::trunc → delete old content (default with ios::out)​

●​ ios::binary → binary mode​

👉 Modes can be combined using | (bitwise OR).


Example:
fstream file("data.txt", ios::in | ios::out | ios::app);

🔹 4. Closing a File
Always close after work:

file.close();

🔹 5. Writing to a File
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream fout("test.txt"); // create & open file
fout << "Hello World!" << endl;
fout << 123 << " " << 45.67;
fout.close();
return 0;
}

●​ Output operators (<<) work just like cout.​

🔹 6. Reading from a File


#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream fin("test.txt"); // open file for reading
string line;
while (getline(fin, line)) { // read line by line
cout << line << endl;
}
fin.close();
return 0;
}

Other methods:

●​ fin >> var; → reads word by word (whitespace separated).​

●​ getline(fin, stringVar); → reads full line.​


●​ fin.get(ch); → reads character by character.​

🔹 7. File Pointers
Each file has two pointers:

●​ get pointer → for reading.​

●​ put pointer → for writing.​

Functions to manipulate pointers:

●​ seekg(pos) → set get pointer.​

●​ seekp(pos) → set put pointer.​

●​ tellg() → get current get pointer position.​

●​ tellp() → get current put pointer position.​

Example:

file.seekg(0, ios::end); // move get pointer to end


int size = file.tellg(); // file size

🔹 8. Reading/Writing Binary Files


Binary I/O uses read() and write() (member functions of fstream).

Writing Binary
#include <iostream>
#include <fstream>
using namespace std;

class Student {
char name[20];
int age;
public:
void getData() {
cout << "Enter name & age: ";
cin >> name >> age;
}
};

int main() {
Student s;
s.getData();
ofstream fout("student.dat", ios::binary);
fout.write((char*)&s, sizeof(s));
fout.close();
}

Reading Binary
#include <iostream>
#include <fstream>
using namespace std;

class Student {
char name[20];
int age;
public:
void display() {
cout << name << " " << age << endl;
}
};

int main() {
Student s;
ifstream fin("student.dat", ios::binary);
fin.read((char*)&s, sizeof(s));
s.display();
fin.close();
}

🔹 9. Error Handling in Files


Functions in ios class:

●​ eof() → true if end-of-file reached.​

●​ fail() → true if operation failed.​

●​ bad() → true if irrecoverable error.​

●​ good() → true if no error.​

Example:

if (!fin) {
cout << "Error opening file!";
}

🔹 10. Append Mode Example


ofstream fout("log.txt", ios::app);
fout << "New entry added!" << endl;

🔹 11. Important Exam-Trap Facts


●​ Default mode of ofstream = ios::out | ios::trunc (clears file).​

●​ Default mode of ifstream = ios::in.​

●​ Default mode of fstream = none, must specify.​

●​ getline() reads till newline → discards \n.​

●​ get() reads including whitespaces.​

●​ Binary files are more efficient but not human-readable.​

●​ Text files are human-readable but slower for structured data.​

●​ Always close() file → otherwise data may not save properly.​

🔹 12. Quick Syntax Recap


Open file:​

file.open("name.txt", ios::in | ios::out);

●​

Close file:​

file.close();

●​
●​ Write: fout << "data";​

●​ Read: fin >> var;​

●​ Binary Write: fout.write((char*)&obj, sizeof(obj));​

●​ Binary Read: fin.read((char*)&obj, sizeof(obj));​

●​ Pointer movement:​

○​ seekg(offset, dir)​

○​ seekp(offset, dir)​
○​ tellg(), tellp()​

You might also like