-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFile in java
More file actions
86 lines (71 loc) · 3.3 KB
/
File in java
File metadata and controls
86 lines (71 loc) · 3.3 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package taoshiflex.practice;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class Practice {
public static void main(String[] args) {
// Input: Number of students
try (Scanner in = new Scanner(System.in)) {
// Input: Number of students
System.out.print("Enter the number of students: ");
int n = in.nextInt();
in.nextLine(); // Consume the leftover newline
// File paths
String directoryPath = "E:\\University";
String filePath = directoryPath + "\\Student.txt";
// ArrayList to store student details
ArrayList<String> studentDataList = new ArrayList<>();
try {
// Create directory
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdir();
System.out.println("Directory created: " + directoryPath);
}
// Generate student data
Random random = new Random();
Set<String> uniqueIDs = new HashSet<>();
for (int i = 1; i <= n; i++) {
String firstName = "FirstName" + i;
String lastName = "LastName" + i;
int yearOfAdmission = random.nextInt(2024 - 2012 + 1) + 2012;
String id;
do {
int randomPart = 1000 + random.nextInt(9000); // Random 4-digit number
id = yearOfAdmission + String.valueOf(randomPart);
} while (uniqueIDs.contains(id)); // Ensure ID uniqueness
uniqueIDs.add(id);
// Add student details to the list
String studentData = firstName + " " + lastName + " " + yearOfAdmission + " " + id;
studentDataList.add(studentData);
}
try ( // Write to file using BufferedWriter
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (String studentData : studentDataList) {
writer.write(studentData);
writer.newLine();
}
}
System.out.println("Student data written successfully to " + filePath);
// Read from file using BufferedReader
System.out.println("\nReading data from file:");
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
}