-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram that writes an Serial No.(int), First Name (String), CGPA.txt
More file actions
47 lines (46 loc) · 1.48 KB
/
program that writes an Serial No.(int), First Name (String), CGPA.txt
File metadata and controls
47 lines (46 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWriteExample {
public static void main(String[] args) {
String filePath =
"C:\Users\harsh\OneDrive\Desktop\harshajava\Program.txt";
// Write student data to file
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(filePath))) {
// Student data
int serialNo = 1;
String firstName = "John";
float cgpa = 3.75f;
char grade = 'A';
// Write student data to file
writer.write(serialNo + "," + firstName + "," + cgpa + "," +
grade);
writer.newLine();
System.out.println("Student data written to the file
successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file: " + e.getMessage());
}
// Read student data from file
try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] studentData = line.split(",");
int serialNo = Integer.parseInt(studentData[0]);
String firstName = studentData[1];
float cgpa = Float.parseFloat(studentData[2]);
char grade = studentData[3].charAt(0);
System.out.println("Serial No: " + serialNo);
System.out.println("First Name: " + firstName);
System.out.println("CGPA: " + cgpa);
System.out.println("Grade: " + grade);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file: "
+ e.getMessage());
} } }