panaewboi

io StudentDataStream 28-10-2019

Oct 28th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.38 KB | None | 0 0
  1. package club.iostream;
  2.  
  3. import club.model.Student;
  4. import java.io.DataInputStream;
  5. import java.io.DataOutputStream;
  6. import java.io.FileInputStream;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.time.LocalDate;
  10.  
  11. public class StudentDataStream {
  12.    
  13.     public static void writeStudentData (String fileName, Student[] students) {
  14.         try (FileOutputStream fos = new FileOutputStream (fileName);
  15.             DataOutputStream dos = new DataOutputStream(fos)) {
  16.             for (int i=0; i<students.length; i++) {
  17.                 Student student = students[i];
  18.                 dos.writeLong(student.getStudentId());
  19.                 dos.writeUTF(student.getStudentName());
  20.             }
  21.         } catch (IOException ex) {
  22.             System.out.println(ex.getMessage());
  23.         }
  24.        
  25.     }
  26.    
  27.     public static void readStudentData (String fileName) {
  28.         try (FileInputStream fis = new FileInputStream(fileName);
  29.             DataInputStream dis = new DataInputStream(fis)) {
  30.             while (dis.available()!=0){
  31.                 long readId = dis.readLong();
  32.                 String readName = dis.readUTF();
  33.                 System.out.println("Id: " + readId + ", " + "Name: " + readName);
  34.             }
  35.         } catch (IOException ex) {
  36.             System.out.println(ex.getMessage());
  37.        
  38.         }
  39.     }
  40.    
  41.     public static Student[] genStudent(int size) {
  42.         Student genStudent[] = new Student[size];
  43.         for (int i=0; i<size; i++) {
  44.             long id = 61100+((int)(Math.random()*99) +1);
  45.             int ch1 = ((int) (Math.random() * (90-65+1))) + 65;
  46.             int ch2 = ((int) (Math.random() * (90-65+1))) + 65;
  47.             int ch3 = ((int) (Math.random() * (90-65+1))) + 65;
  48.             String name = "S" + (char)ch1 + (char)ch2 + (char)ch3;
  49.             genStudent[i] = new Student(id,name);
  50.         }
  51.         return genStudent;
  52.     }    
  53.    
  54.     public static void printStudentList(Student[] stdList) {
  55.         for (int i=0; i<stdList.length; i++) {
  56.             System.out.println(stdList[i]);
  57.         }
  58.     }
  59.    
  60.    
  61.     public static void main(String[] args) {
  62.        Student[] studentList = genStudent(10);
  63.        printStudentList(studentList);
  64.        writeStudentData("studentlist" + "-" + LocalDate.now()+".dat",studentList);
  65.        readStudentData("studentlist-2019-10-28.dat");
  66.     }
  67.    
  68. }
Add Comment
Please, Sign In to add comment