Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package club.iostream;
- import club.model.Student;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.time.LocalDate;
- public class StudentDataStream {
- public static void writeStudentData (String fileName, Student[] students) {
- try (FileOutputStream fos = new FileOutputStream (fileName);
- DataOutputStream dos = new DataOutputStream(fos)) {
- for (int i=0; i<students.length; i++) {
- Student student = students[i];
- dos.writeLong(student.getStudentId());
- dos.writeUTF(student.getStudentName());
- }
- } catch (IOException ex) {
- System.out.println(ex.getMessage());
- }
- }
- public static void readStudentData (String fileName) {
- try (FileInputStream fis = new FileInputStream(fileName);
- DataInputStream dis = new DataInputStream(fis)) {
- while (dis.available()!=0){
- long readId = dis.readLong();
- String readName = dis.readUTF();
- System.out.println("Id: " + readId + ", " + "Name: " + readName);
- }
- } catch (IOException ex) {
- System.out.println(ex.getMessage());
- }
- }
- public static Student[] genStudent(int size) {
- Student genStudent[] = new Student[size];
- for (int i=0; i<size; i++) {
- long id = 61100+((int)(Math.random()*99) +1);
- int ch1 = ((int) (Math.random() * (90-65+1))) + 65;
- int ch2 = ((int) (Math.random() * (90-65+1))) + 65;
- int ch3 = ((int) (Math.random() * (90-65+1))) + 65;
- String name = "S" + (char)ch1 + (char)ch2 + (char)ch3;
- genStudent[i] = new Student(id,name);
- }
- return genStudent;
- }
- public static void printStudentList(Student[] stdList) {
- for (int i=0; i<stdList.length; i++) {
- System.out.println(stdList[i]);
- }
- }
- public static void main(String[] args) {
- Student[] studentList = genStudent(10);
- printStudentList(studentList);
- writeStudentData("studentlist" + "-" + LocalDate.now()+".dat",studentList);
- readStudentData("studentlist-2019-10-28.dat");
- }
- }
Add Comment
Please, Sign In to add comment