jAVA EXP 9
jAVA EXP 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;
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());
}
}
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
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;
dos.writeUTF(name);
dos.writeInt(age);
dos.writeDouble(weight);
dos.writeDouble(height);
dos.writeUTF(city);
dos.writeUTF(phone);
} 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)) {
import java.io.*;
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
}
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
Number of vowels: 32
Number of words: 20
Number of times 'a' occurred: 8