Advertisement
Guest User

Untitled

a guest
May 25th, 2019
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.78 KB | None | 0 0
  1.     public static void  writeRectangleArrayToBinaryFile(File file, Rectangle[] rects ) {
  2.         try(DataOutputStream oos = new DataOutputStream(new FileOutputStream(file))) {
  3.             for (int i = 0; i < rects.length; i++) {
  4.                 oos.writeInt(rects[i].getTopLeft().getX());
  5.                 oos.writeInt(rects[i].getTopLeft().getY());
  6.                 oos.writeInt(rects[i].getBottomRight().getX());
  7.                 oos.writeInt(rects[i].getBottomRight().getY());
  8.             }
  9.         } catch (IOException ex){
  10.             ex.printStackTrace();
  11.         }
  12.     }
  13. //    Записывает массив из Rectangle в двоичный файл, имя файла задается экземпляром класса File.
  14.  
  15.     public static Rectangle[]  readRectangleArrayFromBinaryFileReverse(File file) {
  16.         Rectangle[] rects = null;
  17.         final int byteToIntProportion = 16;
  18.         try(DataInputStream ois = new DataInputStream(new FileInputStream(file)))
  19.         {
  20.             int i = ois.available()/byteToIntProportion-1;
  21.             rects = new Rectangle[ois.available()/byteToIntProportion];
  22.             while (ois.available()>0) {
  23.                 int x1 = ois.readInt();
  24.                 int y1 = ois.readInt();
  25.                 int x2 = ois.readInt();
  26.                 int y2 = ois.readInt();
  27.                 rects[i] = new Rectangle(x1, y1, x2, y2);
  28.                 i--;
  29.             }
  30.         } catch(IOException ex){
  31.             ex.printStackTrace();
  32.         } finally {
  33.             return rects;
  34.         }
  35.     }
  36. //    Предполагается, что данные в файл записаны в формате предыдущего упражнения.
  37. //    Метод читает вначале данные о последнем записанном в файл Rectangle и создает
  38. //    на их основе экземпляр Rectangle, затем читает данные следующего с конца Rectangle
  39. //    и создает на их основе экземпляр Rectangle и т.д.  вплоть до данных для самого первого записанного
  40. //    в файл Rectangle. Из созданных таким образом экземпляров Rectangle создается массив, который и возвращает метод.
  41.  
  42.     public static void  writeRectangleToTextFileOneLine(File file, Rectangle rect) {
  43.         try(FileWriter writer = new FileWriter(file, false)) {
  44.             writer.write(rect.getTopLeft().getX()+" "+rect.getTopLeft().getY()+" "
  45.                     +rect.getBottomRight().getX()+" "+rect.getBottomRight().getY());
  46.             writer.flush();
  47.         } catch(IOException ex){
  48.             ex.printStackTrace();
  49.         }
  50.     }
  51. //    Записывает Rectangle в текстовый файл в одну строку, имя файла задается экземпляром класса File.
  52. //    Поля в файле разделяются пробелами.
  53.  
  54.     public static Rectangle  readRectangleFromTextFileOneLine(File file) {
  55.         Rectangle rect = null;
  56.         try(BufferedReader br = new BufferedReader (new FileReader(file))) {
  57.             String[] arrRect = br.readLine().split(" ");
  58.             rect = new Rectangle(Integer.parseInt(arrRect[0]),Integer.parseInt(arrRect[1]),
  59.                     Integer.parseInt(arrRect[2]),Integer.parseInt(arrRect[3]));
  60.         } catch (IOException ex) {
  61.             ex.printStackTrace();
  62.         } finally {
  63.             return rect;
  64.         }
  65.     }
  66. //    Читает данные для Rectangle из текстового файла и создает на их основе экземпляр Rectangle,
  67. //    имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
  68.  
  69.     public static void  writeRectangleToTextFileFourLines(File file, Rectangle rect) {
  70.         try(FileWriter writer = new FileWriter(file, false)) {
  71.             writer.write(rect.getTopLeft().getX()+"\n"+rect.getTopLeft().getY()+"\n"
  72.                     +rect.getBottomRight().getX()+"\n"+rect.getBottomRight().getY());
  73.             writer.flush();
  74.         } catch(IOException ex){
  75.             ex.printStackTrace();
  76.         }
  77.     }
  78. //    Записывает Rectangle в текстовый файл, каждое число в отдельной строке , имя файла задается экземпляром класса File.
  79.  
  80.     public static Rectangle  readRectangleFromTextFileFourLines(File file) {
  81.         Rectangle rect = null;
  82.         try(BufferedReader br = new BufferedReader (new FileReader(file))) {
  83.             rect = new Rectangle(Integer.parseInt(br.readLine()),Integer.parseInt(br.readLine()),
  84.                     Integer.parseInt(br.readLine()),Integer.parseInt(br.readLine()));
  85.         } catch (IOException ex) {
  86.             ex.printStackTrace();
  87.         } finally {
  88.             return rect;
  89.         }
  90.     }
  91. //    Читает данные для Rectangle из текстового файла и создает на их основе экземпляр Rectangle,
  92. //    имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
  93.  
  94.     public static void  writeTraineeToTextFileOneLine(File file, Trainee trainee) {
  95.         try(OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8")) {
  96.             writer.write(trainee.getFirstName()+" "+trainee.getLastName()+" "+trainee.getRating());
  97.             writer.flush();
  98.         } catch (FileNotFoundException ex) {
  99.             ex.printStackTrace();
  100.         } catch (UnsupportedEncodingException ex) {
  101.             ex.printStackTrace();
  102.         } catch(IOException ex) {
  103.             ex.printStackTrace();
  104.         }
  105.     }
  106. //    Записывает Trainee в текстовый файл в одну строку в кодировке UTF-8, имя файла задается экземпляром класса File. Имя, фамилия и оценка в файле разделяются пробелами.
  107.  
  108.     public static Trainee  readTraineeFromTextFileOneLine(File file) {
  109.         Trainee trainee = null;
  110.         try(BufferedReader br = new BufferedReader (new FileReader(file))) {
  111.             String[] arrRect = br.readLine().split(" ");
  112.             trainee = new Trainee(arrRect[0],arrRect[1],Integer.parseInt(arrRect[2]));
  113.         } catch (IOException ex) {
  114.             ex.printStackTrace();
  115.         } finally {
  116.             return trainee;
  117.         }
  118.     }
  119. //    Читает данные для Trainee из текстового файла и создает на их основе экземпляр Trainee, имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
  120.  
  121.     public static void  writeTraineeToTextFileThreeLines(File file, Trainee trainee) {
  122.         try(OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8")) {
  123.             writer.write(trainee.getFirstName()+"\n"+trainee.getLastName()+"\n"+trainee.getRating());
  124.             writer.flush();
  125.         } catch (FileNotFoundException ex) {
  126.             ex.printStackTrace();
  127.         } catch (UnsupportedEncodingException ex) {
  128.             ex.printStackTrace();
  129.         } catch(IOException ex) {
  130.             ex.printStackTrace();
  131.         }
  132.     }
  133. //    Записывает Trainee в текстовый файл в кодировке UTF-8, каждое поле в отдельной строке, имя файла задается экземпляром класса File.
  134.  
  135.     public static Trainee  readTraineeFromTextFileThreeLines(File file) {
  136.         Trainee trainee = null;
  137.         try(BufferedReader br = new BufferedReader (new FileReader(file))) {
  138.             trainee = new Trainee(br.readLine(),br.readLine(),Integer.parseInt(br.readLine()));
  139.         } catch (IOException ex) {
  140.             ex.printStackTrace();
  141.         } finally {
  142.             return trainee;
  143.         }
  144.     }
  145. //    Читает данные для Trainee из текстового файла и создает на их основе экземпляр Trainee, имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
  146.  
  147.     public static void  serializeTraineeToBinaryFile(File file, Trainee trainee) {
  148.         try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
  149.             oos.writeObject(trainee);
  150.         } catch (Exception ex){
  151.             ex.printStackTrace();
  152.         }
  153.     }
  154. //    Сериализует Trainee в двоичный файл, имя файла задается экземпляром класса File.
  155.  
  156.     public static Trainee  deserializeTraineeFromBinaryFile(File file) {
  157.         Trainee trainee = null;
  158.         try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
  159.             Trainee p=(Trainee) ois.readObject();
  160.         } catch(Exception ex){
  161.             ex.printStackTrace();
  162.         } finally {
  163.             return trainee;
  164.         }
  165.     }
  166. //    Десериализует Trainee из двоичного файла, имя файла задается экземпляром класса File.
  167. //    Предполагается, что данные в файл записаны в формате предыдущего упражнения.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement