Object Oriented Programming-I (3140705) Enrollment Number 220210107041
Experiment No: 7
AIM: To demonstrate I/O from files.
Date:
CO mapped: CO-4
Objectives:
To showcase proficiency in reading data from and writing data to files in various formats
using programming languages, demonstrating the ability to implement reliable and
efficient file I/O operations, which are essential for tasks such as data storage, retrieval,
and processing in software applications.
Background:
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operations fast. The java.io package contains all the classes
required for input and output operations.
Practical questions:
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
1. Write a program that removes all the occurrences of a specified string from a text file.
For example, invoking java Practical7_1 John filename removes the string John from the
specified file. Your program should read the string as an input.
import java.io.*;
public class Pra07_1 {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java RemoveStringFromFile <string_to_remove>
<filename>");
return;
}
String stringToRemove = args[0];
String filename = args[1];
try {
File inputFile = new File(filename);
File tempFile = new File("tempfile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.replaceAll(stringToRemove, "");
writer.write(line + System.getProperty("line.separator"));
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
System.out.println("Occurrences of '" + stringToRemove + "' removed from the file.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
2. Write a program that will count the number of characters, words, and lines in a file.
Words are separated by whitespace characters. The file name should be passed as a
command-line argument.
import java.io.*;
public class Pra07_2 {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java FileStatsCounter <filename>");
return;
}
String filename = args[0];
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
lineCount++;
charCount += line.length();
String[] words = line.split("\\s+");
wordCount += words.length;
}
reader.close();
System.out.println("Character count: " + charCount);
System.out.println("Word count: " + wordCount);
System.out.println("Line count: " + lineCount);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
3. Write a program to create a file named Practical7.txt if it does not exist. Write 100
integers created randomly into the file. Integers are separated by spaces in the file. Read
the data back from the file and display the data in increasing order.
import java.io.*;
import java.util.*;
public class Pra07_3 {
public static void main(String[] args) {
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107041)");
System.out.println("Name: (Keval Parmar)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
try {
File file = new File("Practical7.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
Random random = new Random();
for (int i = 0; i < 100; i++) {
int num = random.nextInt(1000); // Generate random integers between 0 and 999
writer.write(num + " ");
}
writer.close();
FileReader reader = new FileReader(file);
Scanner scanner = new Scanner(reader);
List<Integer> numbers = new ArrayList<>();
while (scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
reader.close();
Collections.sort(numbers);
System.out.println("Integers in increasing order:");
for (int num : numbers) {
System.out.print(num + " ");
}
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Quiz: (Sufficient space to be provided for the answers)
1. What is file input/output (I/O), and why is it important in software development?
File Input/Output (I/O) refers to the process of reading from and writing to files in a computer
system. It's a crucial aspect of software development for several reasons:
1. Data Persistence: Files allow data to be stored beyond the program's execution. This
persistence is essential for saving user preferences, application state, and other critical
information.
2. Data Exchange: Files facilitate communication between different programs or components.
For instance, a web server reads HTML files to serve web pages, and a database system reads
and writes data to files.
3. Configuration and Settings: Many applications use files (e.g., JSON, XML, or INI files) to
store configuration settings. These files allow users to customize the behavior of the software.
4. Logging and Debugging: Writing log files helps developers track errors, monitor
performance, and diagnose issues. Log files are essential for debugging and maintaining
software.
5. Data Transformation: Files are used to import/export data between different formats (e.g.,
CSV, JSON, XML). This is crucial for data integration and migration.
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
In summary, file I/O enables data persistence, inter-process communication, and configuration
management, making it a fundamental part of software development.
2. What are the common modes for opening files, and how do they differ (e.g., read, write,
append)?
1. Read Mode ('r'):
- Allows reading data from the file.
- File pointer starts at the beginning.
- Raises an error if the file doesn't exist.
- Commonly used for reading text files, configuration files, etc.
2. Write Mode ('w'):
- Allows writing data to the file.
- Creates a new file if it doesn't exist.
- Overwrites existing content.
- Use with caution to avoid data loss.
3. Append Mode ('a'):
- Allows writing data to the end of the file.
- Creates a new file if it doesn't exist.
- Preserves existing content.
- Useful for adding data to log files or maintaining records.
3. Describe the concept of file streams and how they are used in file I/O operations.
Certainly! Let's dive into the concept of **file streams** and their role in file I/O operations:
- File Streams:
- A file stream represents a connection between a program and a file.
- It acts as a conduit through which data flows between the program and the file.
- Streams provide an abstraction layer, allowing developers to read from or write to files
without worrying about low-level details.
- Types of File Streams:
1. Input Streams (Read Streams):
- Used for reading data from files.
- Provide methods to read characters, bytes, or other data types.
- Examples: ifstream in C++, FileReader in Java.
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
2. Output Streams (Write Streams):
- Used for writing data to files.
- Provide methods to write characters, bytes, or other data types.
- Examples: ofstream in C++, FileWriter in Java.
- How They Are Used:
- Open a file stream with the desired mode (read, write, or append).
- Read or write data using stream methods (e.g., read(), write(), getline()).
- Close the stream when done to release resources.
In summary, file streams simplify file I/O by providing a high-level interface for reading and
writing data to files.
4. Write short notes about I/O stream classes.
1. Byte Streams:
- Handle raw binary data.
- Examples: FileInputStream, FileOutputStream.
- Used for reading/writing bytes directly.
2. Character Streams:
- Handle character data and handle character set translation.
- Examples: FileReader, FileWriter.
- Automatically convert between bytes and characters.
3. Buffered Streams:
- Optimize I/O by reducing native API calls.
- Examples: BufferedReader, BufferedWriter.
- Improve performance by buffering data.
4. Scanning and Formatting:
- Allows reading and writing formatted text.
- Useful for parsing and formatting data.
Remember, streams represent input sources or output destinations, including files, devices, and
memory arrays. They handle various data types, making I/O efficient and flexible!
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Object Oriented Programming-I (3140705) Enrollment Number 220210107041
References used by the students: (Sufficient space to be provided)
Rubric wise marks obtained:
Rubrics Criteria Need Good Excellent Total
Improvement
Marks Design of Program has Program has slight Program is
logic (4) significant logic errors that do logically well
logic errors. no significantly designed (3)
Correct (1) affect the results
output (4) (2)
Output has
Mock viva multiple Output has minor Program
test (2) errors. (1) errors. (2) displays correct
output with no
Delayed & Partially correct errors (3)
only few response (1)
correct All questions
answers (1) responded
Correctly (2)
Signature of Faculty: