0% found this document useful (0 votes)
21 views11 pages

jAVA EXP 9

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)
21 views11 pages

jAVA EXP 9

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/ 11

Experiment 9

Q1. Take file name as input to your program through command line. If file
exists, then open it and display contents of the file. After displaying contents of
file ask user – do you want to add the data at the end of file. If user response is
“Yes”, then accept data from user and append it to file. If file in not existing
then create a fresh new-file and store user data into it. User should type “exit”
on new line to stop the program. Do this program using Character stream
classes

import java.io.*;
import java.util.Scanner;

public class FileHandler {


public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please provide the file name as a command-line
argument.");
return;
}

String fileName = args[0];


File file = new File(fileName);

try (Scanner scanner = new Scanner(System.in)) {


// Check if the file exists
if (file.exists()) {
System.out.println("File exists. Contents of the file:");
displayFileContents(file);

// Ask the user if they want to append data to the file


System.out.print("\nDo you want to add data at the end of the file?
(Yes/No): ");
String response = scanner.nextLine();

if (response.equalsIgnoreCase("Yes")) {
appendDataToFile(file, scanner);
}
} else {
System.out.println("File does not exist. Creating a new file.");
appendDataToFile(file, scanner);
}

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}

// Method to display file contents


private static void displayFileContents(File file) throws IOException {
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
}
// Method to append data to file
private static void appendDataToFile(File file, Scanner scanner) throws
IOException {
try (FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {

System.out.println("Enter data to append to the file (type 'exit' on a new line


to stop):");

while (true) {
String data = scanner.nextLine();
if (data.equalsIgnoreCase("exit")) {
break;
}
bufferedWriter.write(data);
bufferedWriter.newLine();
}
}
System.out.println("Data has been written to the file successfully.");
}
}

OUTPUT:
PS D:\JAVA_PROGRAMMING> javac FileHandler.java
PS D:\JAVA_PROGRAMMING> java FileHandler
Ram.txt

File does not exist. Creating a new file.


Enter data to append to the file (type 'exit' on a new line to stop):
My full name is Ram Ganesh Mane
exit
Data has been written to the file successfully.
PS D:\JAVA_PROGRAMMING> java FileHandler
Ram.txt

File exists. Contents of the file:


My full name is Ram Ganesh Mane

Do you want to add data at the end of the file? (Yes/No): Yes
Enter data to append to the file (type 'exit' on a new line to stop):
I am in 3rd year of Data Science Engineering. My College is DYPCET.
exit
Data has been written to the file successfully.
Q2. Take Student information such as name, age, weight, height, city, phone
from user and store it in the file using DataOutputStream and
FileOutputStream and Retrive data using DataInputStream and
FileInputStream and display the result.

import java.io.*;
import java.util.Scanner;

public class StudentInfoHandler {


public static void main(String[] args) {
String fileName = "student_info.dat";
Scanner scanner = new Scanner(System.in);

// Taking user input for student information


System.out.print("Enter Student Name: ");
String name = scanner.nextLine();

System.out.print("Enter Age: ");


int age = scanner.nextInt();

System.out.print("Enter Weight (in kg): ");


double weight = scanner.nextDouble();

System.out.print("Enter Height (in cm): ");


double height = scanner.nextDouble();
scanner.nextLine(); // Consume newline left-over

System.out.print("Enter City: ");


String city = scanner.nextLine();

System.out.print("Enter Phone Number: ");


String phone = scanner.nextLine();

// Store data to file


try (FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream dos = new DataOutputStream(fos)) {

dos.writeUTF(name);
dos.writeInt(age);
dos.writeDouble(weight);
dos.writeDouble(height);
dos.writeUTF(city);
dos.writeUTF(phone);

System.out.println("\nStudent information has been written to the file


successfully.");

} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " +
e.getMessage());
}
// Retrieve data from file and display it
try (FileInputStream fis = new FileInputStream(fileName);
DataInputStream dis = new DataInputStream(fis)) {

String storedName = dis.readUTF();


int storedAge = dis.readInt();
double storedWeight = dis.readDouble();
double storedHeight = dis.readDouble();
String storedCity = dis.readUTF();
String storedPhone = dis.readUTF();

System.out.println("\nRetrieved Student Information:");


System.out.println("Name: " + storedName);
System.out.println("Age: " + storedAge);
System.out.println("Weight: " + storedWeight + " kg");
System.out.println("Height: " + storedHeight + " cm");
System.out.println("City: " + storedCity);
System.out.println("Phone: " + storedPhone);
} catch (IOException e) {
System.out.println("An error occurred while reading from the file: " +
e.getMessage());
}
scanner.close();
}}
OUTPUT:
PS D:\JAVA_PROGRAMMING> javac StudentInfoHandler.java

PS D:\JAVA_PROGRAMMING> java StudentInfoHandler

Enter Student Name: Ram Ganesh Mane


Enter Age: 21
Enter Weight (in kg): 61
Enter Height (in cm): 157
Enter City: Kolhapur
Enter Phone Number: 1232456789

Student information has been written to the file successfully.

Retrieved Student Information:


Name: Ram Ganesh Mane
Age: 21
Weight: 61.0 kg
Height: 157.0 cm
City: Kolhapur
Phone: 1232456789
Q3. Write a Java program to read text file and find number of vowels, number
of words from it. Also find number of times ‘a’ occurred in text file.

import java.io.*;

public class TextFileAnalysis {


public static void main(String[] args) {
String fileName = "Ram.txt";
int vowelCount = 0;
int wordCount = 0;
int aCount = 0;

try (FileReader fileReader = new FileReader(fileName);


BufferedReader bufferedReader = new BufferedReader(fileReader)) {

String line;
while ((line = bufferedReader.readLine()) != null) {
wordCount += line.split("\\s+").length; // Counting words
vowelCount += countVowels(line); // Counting vowels
aCount += countOccurrencesOfA(line); // Counting 'a' occurrences
}

System.out.println("Number of vowels: " + vowelCount);


System.out.println("Number of words: " + wordCount);
System.out.println("Number of times 'a' occurred: " + aCount);
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " +
e.getMessage());
}
}

// Method to count vowels in a line


private static int countVowels(String line) {
int count = 0;
for (char ch : line.toLowerCase().toCharArray()) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
return count;
}

// Method to count occurrences of 'a' in a line


private static int countOccurrencesOfA(String line) {
int count = 0;
for (char ch : line.toLowerCase().toCharArray()) {
if (ch == 'a') {
count++;
}
}
return count;
}
}

Ram.txt
My full name is Ram Ganesh Mane
I am in 3rd year of Data Science Engineering. My College is DYPCET.

OUTPUT:
PS D:\JAVA_PROGRAMMING> javac TextFileAnalysis.java

PS D:\JAVA_PROGRAMMING> java TextFileAnalysis

Number of vowels: 32
Number of words: 20
Number of times 'a' occurred: 8

You might also like