Advertisement
Guest User

CSVDatabase

a guest
Mar 22nd, 2016
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.06 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class _08CSVDatabase {
  5.     private static final String STUDENTS_PATH = "resources/students.txt";
  6.     private static final String GRADES_PATH = "resources/grades.txt";
  7.     private static File studentsFile = new File(STUDENTS_PATH);
  8.     private static File gradesFile = new File(GRADES_PATH);
  9.  
  10.     public static void main(String[] args) {
  11.  
  12.         Scanner sc = new Scanner(System.in);
  13.         String command;
  14.         System.out.println("Insert one of these commands (add student,add grades, search, delete, update, exit): ");
  15.         while (!(command = sc.nextLine().toLowerCase()).equals("exit")) {
  16.             if (command.equals("add student")) {
  17.                 System.out.println("Insert full name,age and hometown in the following format(full name,age,hometown): ");
  18.                 command = sc.nextLine();
  19.                 String[] commandArgs = command.split(",");
  20.                 insertStudent(commandArgs[0], commandArgs[1], commandArgs[2]);
  21.             }else if(command.equals("add grades")){
  22.                 System.out.println("Insert id of the student and what grade to insert in format(id,grade): ");
  23.                 command = sc.nextLine();
  24.                 String[] commandArgs = command.split(",");
  25.                 insertGradesById(commandArgs[0], commandArgs[1]);
  26.             } else if (command.equals("search")) {
  27.                 System.out.println("Search by full name or id in: ");
  28.                 command = sc.nextLine();
  29.                 if (command.equals("full name")) {
  30.                     System.out.println("Insert name: ");
  31.                     command = sc.nextLine().toLowerCase();
  32.                     searchByIdOrName(command, "full name");
  33.                 } else if (command.equals("id")) {
  34.                     System.out.println("Insert id: ");
  35.                     command = sc.nextLine();
  36.                     searchByIdOrName(command, "id");
  37.                 } else {
  38.                     System.out.println("No such search demand");
  39.                 }
  40.             } else if (command.equals("delete")) {
  41.                 System.out.println("Insert id to delete: ");
  42.                 command = sc.nextLine();
  43.                 deleteById(command);
  44.             } else if (command.equals("update")) {
  45.                 System.out.println("Insert id to update: ");
  46.                 String id = sc.nextLine();
  47.                 System.out.println("Insert what to update information or grades: ");
  48.                 String updateDemand = sc.nextLine();
  49.                 if (updateDemand.equals("information")) {
  50.                     System.out.println("Type what information to update name,age or hometown: ");
  51.                     String whatToUpdate = sc.nextLine();
  52.                     String updateInfo = "";
  53.                     if (whatToUpdate.equals("name")) {
  54.                         System.out.println("Type first and last name separated with white space: ");
  55.                         updateInfo = sc.nextLine();
  56.                     } else if (whatToUpdate.equals("age")) {
  57.                         System.out.println("Type new age: ");
  58.                         updateInfo = sc.nextLine();
  59.                     } else if (whatToUpdate.equals("hometown")) {
  60.                         System.out.println("Type new hometown: ");
  61.                         updateInfo = sc.nextLine();
  62.                     } else {
  63.                         System.out.println("There is no such field !");
  64.                     }
  65.                     updateById(id, "info", whatToUpdate + " " + updateInfo);
  66.                 } else if (updateDemand.equals("grades")) {
  67.                     System.out.println("Type what subject and grade to update in format (subject grade):");
  68.                     command = sc.nextLine();
  69.                     updateById(id, "grades", command);
  70.                 } else {
  71.                     System.out.println("You can only update student information and grades");
  72.                 }
  73.             } else {
  74.                 System.out.println("Wrong command try again !");
  75.             }
  76.             System.out.println("---------------------------");
  77.             System.out.println("Insert one of these commands (add student,add grades, search, delete, update, exit): ");
  78.  
  79.         }
  80. //        insertStudent("Stefka Koynova" , 50 , "Ruse" );
  81. //        insertGradesById("3", "Music 6.00");
  82. //        searchByIdOrName("Desislava Koynova", "full name");
  83. //        searchByIdOrName("2", "id");
  84. //        deleteById("5");
  85. //        updateById("2", "grades", "Math 5.59");
  86. //        updateById("2", "grades", "Science 5.59");
  87. //        updateById("2", "info", "name Kalin Vesov");
  88. //        updateById("2", "info", "age 20");
  89. //        updateById("1", "info", "hometown Sofia");
  90.  
  91.     }
  92.  
  93.     private static void insertStudent(String fullName, String age, String homeTown) {
  94.         try (BufferedWriter bw = new BufferedWriter(new FileWriter(studentsFile, true))) {
  95.             int studentId;
  96.             BufferedReader br = new BufferedReader(new FileReader(studentsFile));
  97.             String firstLine = br.readLine();
  98.             boolean noStudents = firstLine == null || firstLine.equals("");
  99.             if (noStudents) {
  100.                 studentId = 1;
  101.             } else {
  102.                 String line;
  103.                 String last = firstLine;
  104.                 while ((line = br.readLine()) != null && !line.equals("")) {
  105.                     last = line;
  106.                 }
  107.                 studentId = Integer.parseInt(last.split(",")[0]) + 1;
  108.             }
  109.             br.close();
  110.             String firstName = fullName.split(" ")[0];
  111.             String lastName = fullName.split(" ")[1];
  112.             String currentStudent = String.format("%d,%s,%s,%s,%s"
  113.                     , studentId, firstName, lastName, age, homeTown);
  114.             PrintWriter pw = new PrintWriter(bw, true);
  115.             pw.println(currentStudent);
  116.             System.out.println("Insert completed !");
  117.  
  118.         } catch (IOException e) {
  119.             e.printStackTrace();
  120.         }
  121.     }
  122.  
  123.     private static void insertGradesById(String studentId, String grade) {
  124.         BufferedReader br;
  125.         try {
  126.             br = new BufferedReader(new FileReader(studentsFile));
  127.             boolean studentExist = false;
  128.             String line;
  129.             while ((line = br.readLine()) != null) {
  130.                 String id = line.split(",")[0];
  131.                 if (studentId.equals(id)) {
  132.                     studentExist = true;
  133.                     break;
  134.                 }
  135.             }
  136.             if (studentExist) {
  137.                 br = new BufferedReader(new FileReader(gradesFile));
  138.                 String currentLine;
  139.                 boolean gradesLineExist = false;
  140.  
  141.                 while ((currentLine = br.readLine()) != null) {
  142.                     String id = currentLine.split(",")[0];
  143.                     if (studentId.equals(id)) {
  144.                         gradesLineExist = true;
  145.                         break;
  146.                     }
  147.                 }
  148.  
  149.                 if (gradesLineExist) {
  150.                     Map<String, ArrayList<String>> currentGrades = new LinkedHashMap<>();
  151.                     String[] gradesArgs = currentLine.split(",");
  152.                     for (int i = 1; i < gradesArgs.length; i++) {
  153.                         String[] subjectAndGrades = gradesArgs[i].split(" ");
  154.                         String subject = subjectAndGrades[0];
  155.                         if (!currentGrades.containsKey(subject)) {
  156.                             currentGrades.put(subject, new ArrayList<>());
  157.                         }
  158.                         for (int j = 1; j < subjectAndGrades.length; j++) {
  159.                             currentGrades.get(subject).add(subjectAndGrades[j]);
  160.                         }
  161.                     }
  162.                     if (!currentGrades.containsKey(grade.split(" ")[0])) {
  163.                         currentGrades.put(grade.split(" ")[0], new ArrayList<>());
  164.                     }
  165.                     currentGrades.get(grade.split(" ")[0]).add(grade.split(" ")[1]);
  166.                     StringBuilder inputGrades = new StringBuilder();
  167.                     inputGrades = inputGrades.append(studentId).append(",");
  168.                     for (Map.Entry subject : currentGrades.entrySet()) {
  169.                         inputGrades = inputGrades.append(subject.getKey()).append(" ");
  170.                         for (String objectGrade : (ArrayList<String>) subject.getValue()) {
  171.                             inputGrades = inputGrades.append(objectGrade).append(" ");
  172.                         }
  173.                         String trim = inputGrades.toString().trim();
  174.                         inputGrades = new StringBuilder(trim);
  175.                         inputGrades = inputGrades.append(",");
  176.                     }
  177.                     inputGrades = inputGrades.deleteCharAt(inputGrades.length() - 1);
  178.                     br = new BufferedReader(new FileReader(gradesFile));
  179.                     String readLine;
  180.                     List<String> allGrades = new ArrayList<>();
  181.                     while ((readLine = br.readLine()) != null) {
  182.                         String id = readLine.split(",")[0];
  183.                         if (studentId.equals(id)) {
  184.                             allGrades.add(inputGrades.toString());
  185.                         } else {
  186.                             allGrades.add(readLine);
  187.                         }
  188.                     }
  189.  
  190.                     Collections.sort(allGrades);
  191.                     BufferedWriter bw = new BufferedWriter(new FileWriter(gradesFile, false));
  192.                     PrintWriter pw = new PrintWriter(bw, true);
  193.                     allGrades.forEach(pw::println);
  194.                     bw.close();
  195.                 } else {
  196.                     BufferedWriter bw = new BufferedWriter(new FileWriter(gradesFile, true));
  197.                     PrintWriter pw = new PrintWriter(bw, true);
  198.                     String output = String.format("%s,%s", studentId, grade);
  199.                     pw.println(output);
  200.                     bw.close();
  201.                 }
  202.                 System.out.println("Insert completed !");
  203.                 br.close();
  204.             } else {
  205.                 System.out.println("Student does not exist");
  206.             }
  207.         } catch (IOException e) {
  208.             e.printStackTrace();
  209.         }
  210.  
  211.     }
  212.  
  213.     private static void searchByIdOrName(String searchWord, String searchTerm) {
  214.         String firstName = "";
  215.         String lastName = "";
  216.         String searchedId = "";
  217.         if (searchTerm.equals("full name")) {
  218.             firstName = searchWord.split(" ")[0];
  219.             lastName = searchWord.split(" ")[1];
  220.         } else {
  221.             searchedId = searchWord;
  222.         }
  223.         try {
  224.             BufferedReader br = new BufferedReader(new FileReader(studentsFile));
  225.             String line;
  226.             String[] searchedStudent = new String[0];
  227.             boolean studentExist = false;
  228.             while ((line = br.readLine()) != null) {
  229.                 String[] lineArgs = line.split(",");
  230.                 if ((lineArgs[1].toLowerCase().equals(firstName.toLowerCase())
  231.                         && lineArgs[2].toLowerCase().equals(lastName.toLowerCase())
  232.                         && searchTerm.equals("full name"))
  233.                         || lineArgs[0].equals(searchedId) && searchTerm.equals("id")) {
  234.                     studentExist = true;
  235.                     searchedStudent = lineArgs;
  236.                     break;
  237.                 }
  238.             }
  239.             if (studentExist) {
  240.                 System.out.printf("%s %s (age: %s, town: %s)\n"
  241.                         , searchedStudent[1], searchedStudent[2], searchedStudent[3], searchedStudent[4]);
  242.                 br = new BufferedReader(new FileReader(gradesFile));
  243.                 String gradesLine;
  244.                 String[] searchedGrades = new String[0];
  245.                 boolean gradesExist = false;
  246.                 while ((gradesLine = br.readLine()) != null) {
  247.                     if (gradesLine.split(",")[0].equals(searchedStudent[0])) {
  248.                         searchedGrades = gradesLine.split(",");
  249.                         gradesExist = true;
  250.                         break;
  251.                     }
  252.                 }
  253.                 if (gradesExist) {
  254.                     for (int i = 1; i < searchedGrades.length; i++) {
  255.                         String[] grades = searchedGrades[i].split(" ");
  256.                         StringBuilder sb = new StringBuilder();
  257.                         sb = sb.append(grades[0]).append(": ");
  258.                         for (int j = 1; j < grades.length; j++) {
  259.                             sb = sb.append(grades[j]).append(", ");
  260.                         }
  261.                         sb = sb.delete(sb.length() - 2, sb.length());
  262.                         System.out.println("# " + sb.toString());
  263.                     }
  264.                 } else {
  265.                     System.out.println("There is no grades for this student");
  266.                 }
  267.             } else {
  268.                 System.out.println("Student does not exist");
  269.             }
  270.             br.close();
  271.         } catch (FileNotFoundException e) {
  272.             e.printStackTrace();
  273.         } catch (IOException e) {
  274.             e.printStackTrace();
  275.         }
  276.     }
  277.  
  278.     private static void deleteById(String studentId) {
  279.         BufferedReader br;
  280.         try {
  281.             br = new BufferedReader(new FileReader(studentsFile));
  282.             String line;
  283.             StringBuilder newStudents = new StringBuilder();
  284.             boolean studentExist = false;
  285.             while ((line = br.readLine()) != null) {
  286.                 if (!line.split(",")[0].equals(studentId)) {
  287.                     newStudents = newStudents.append(line).append(System.lineSeparator());
  288.                 } else {
  289.                     studentExist = true;
  290.                 }
  291.             }
  292.             newStudents = newStudents.delete(newStudents.length() - 2, newStudents.length());
  293.             if (studentExist) {
  294.                 BufferedWriter bw = new BufferedWriter(new FileWriter(studentsFile));
  295.                 PrintWriter pw = new PrintWriter(bw, true);
  296.                 pw.println(newStudents);
  297.                 br = new BufferedReader(new FileReader(gradesFile));
  298.                 StringBuilder newGrades = new StringBuilder();
  299.                 while ((line = br.readLine()) != null) {
  300.                     if (!line.split(",")[0].equals(studentId)) {
  301.                         newGrades = newGrades.append(line).append(System.lineSeparator());
  302.                     }
  303.                 }
  304.                 newGrades = newGrades.delete(newGrades.length() - 2, newGrades.length());
  305.                 bw = new BufferedWriter(new FileWriter(gradesFile));
  306.                 pw = new PrintWriter(bw, true);
  307.                 pw.println(newGrades);
  308.                 System.out.println("Delete completed !");
  309.                 bw.close();
  310.             } else {
  311.                 System.out.println("Student does not exist");
  312.             }
  313.             br.close();
  314.         } catch (FileNotFoundException e) {
  315.             e.printStackTrace();
  316.         } catch (IOException e) {
  317.             e.printStackTrace();
  318.         }
  319.     }
  320.  
  321.     private static void updateById(String studentId, String whatToUpdate, String update) {
  322.         if (whatToUpdate.equals("grades")) {
  323.             insertGradesById(studentId, update);
  324.         } else {
  325.             BufferedReader br;
  326.             try {
  327.                 br = new BufferedReader(new FileReader(studentsFile));
  328.                 String line;
  329.                 StringBuilder newStudents = new StringBuilder();
  330.                 boolean studentExist = false;
  331.                 while ((line = br.readLine()) != null) {
  332.                     String[] lineArgs = line.split(",");
  333.                     if (!lineArgs[0].equals(studentId)) {
  334.                         newStudents = newStudents.append(line).append(System.lineSeparator());
  335.                     } else {
  336.                         String toUpdate = update.split(" ")[0];
  337.                         if (toUpdate.equals("name")) {
  338.                             String firstName = update.split(" ")[1];
  339.                             String lastName = update.split(" ")[2];
  340.                             String updatedLine = String.format("%s,%s,%s,%s,%s"
  341.                                     , lineArgs[0], firstName, lastName, lineArgs[3], lineArgs[4]);
  342.                             newStudents = newStudents.append(updatedLine).append(System.lineSeparator());
  343.                         } else if (toUpdate.equals("age")) {
  344.                             String age = update.split(" ")[1];
  345.                             String updatedLine = String.format("%s,%s,%s,%s,%s"
  346.                                     , lineArgs[0], lineArgs[1], lineArgs[2], age, lineArgs[4]);
  347.                             newStudents = newStudents.append(updatedLine).append(System.lineSeparator());
  348.                         } else if (toUpdate.equals("hometown")) {
  349.                             String hometown = update.split(" ")[1];
  350.                             String updatedLine = String.format("%s,%s,%s,%s,%s"
  351.                                     , lineArgs[0], lineArgs[1], lineArgs[2], lineArgs[3], hometown);
  352.                             newStudents = newStudents.append(updatedLine).append(System.lineSeparator());
  353.                         }
  354.                         studentExist = true;
  355.                     }
  356.                 }
  357.                 newStudents = newStudents.delete(newStudents.length() - 2, newStudents.length());
  358.                 if (studentExist) {
  359.                     BufferedWriter bw = new BufferedWriter(new FileWriter(studentsFile));
  360.                     PrintWriter pw = new PrintWriter(bw, true);
  361.                     pw.println(newStudents);
  362.                     System.out.println("Update completed !");
  363.                     bw.close();
  364.                 } else {
  365.                     System.out.println("Student does not exist");
  366.                 }
  367.                 br.close();
  368.             } catch (FileNotFoundException e) {
  369.                 e.printStackTrace();
  370.             } catch (IOException e) {
  371.                 e.printStackTrace();
  372.             }
  373.         }
  374.     }
  375. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement