Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void writeRectangleArrayToBinaryFile(File file, Rectangle[] rects ) {
- try(DataOutputStream oos = new DataOutputStream(new FileOutputStream(file))) {
- for (int i = 0; i < rects.length; i++) {
- oos.writeInt(rects[i].getTopLeft().getX());
- oos.writeInt(rects[i].getTopLeft().getY());
- oos.writeInt(rects[i].getBottomRight().getX());
- oos.writeInt(rects[i].getBottomRight().getY());
- }
- } catch (IOException ex){
- ex.printStackTrace();
- }
- }
- // Записывает массив из Rectangle в двоичный файл, имя файла задается экземпляром класса File.
- public static Rectangle[] readRectangleArrayFromBinaryFileReverse(File file) {
- Rectangle[] rects = null;
- final int byteToIntProportion = 16;
- try(DataInputStream ois = new DataInputStream(new FileInputStream(file)))
- {
- int i = ois.available()/byteToIntProportion-1;
- rects = new Rectangle[ois.available()/byteToIntProportion];
- while (ois.available()>0) {
- int x1 = ois.readInt();
- int y1 = ois.readInt();
- int x2 = ois.readInt();
- int y2 = ois.readInt();
- rects[i] = new Rectangle(x1, y1, x2, y2);
- i--;
- }
- } catch(IOException ex){
- ex.printStackTrace();
- } finally {
- return rects;
- }
- }
- // Предполагается, что данные в файл записаны в формате предыдущего упражнения.
- // Метод читает вначале данные о последнем записанном в файл Rectangle и создает
- // на их основе экземпляр Rectangle, затем читает данные следующего с конца Rectangle
- // и создает на их основе экземпляр Rectangle и т.д. вплоть до данных для самого первого записанного
- // в файл Rectangle. Из созданных таким образом экземпляров Rectangle создается массив, который и возвращает метод.
- public static void writeRectangleToTextFileOneLine(File file, Rectangle rect) {
- try(FileWriter writer = new FileWriter(file, false)) {
- writer.write(rect.getTopLeft().getX()+" "+rect.getTopLeft().getY()+" "
- +rect.getBottomRight().getX()+" "+rect.getBottomRight().getY());
- writer.flush();
- } catch(IOException ex){
- ex.printStackTrace();
- }
- }
- // Записывает Rectangle в текстовый файл в одну строку, имя файла задается экземпляром класса File.
- // Поля в файле разделяются пробелами.
- public static Rectangle readRectangleFromTextFileOneLine(File file) {
- Rectangle rect = null;
- try(BufferedReader br = new BufferedReader (new FileReader(file))) {
- String[] arrRect = br.readLine().split(" ");
- rect = new Rectangle(Integer.parseInt(arrRect[0]),Integer.parseInt(arrRect[1]),
- Integer.parseInt(arrRect[2]),Integer.parseInt(arrRect[3]));
- } catch (IOException ex) {
- ex.printStackTrace();
- } finally {
- return rect;
- }
- }
- // Читает данные для Rectangle из текстового файла и создает на их основе экземпляр Rectangle,
- // имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
- public static void writeRectangleToTextFileFourLines(File file, Rectangle rect) {
- try(FileWriter writer = new FileWriter(file, false)) {
- writer.write(rect.getTopLeft().getX()+"\n"+rect.getTopLeft().getY()+"\n"
- +rect.getBottomRight().getX()+"\n"+rect.getBottomRight().getY());
- writer.flush();
- } catch(IOException ex){
- ex.printStackTrace();
- }
- }
- // Записывает Rectangle в текстовый файл, каждое число в отдельной строке , имя файла задается экземпляром класса File.
- public static Rectangle readRectangleFromTextFileFourLines(File file) {
- Rectangle rect = null;
- try(BufferedReader br = new BufferedReader (new FileReader(file))) {
- rect = new Rectangle(Integer.parseInt(br.readLine()),Integer.parseInt(br.readLine()),
- Integer.parseInt(br.readLine()),Integer.parseInt(br.readLine()));
- } catch (IOException ex) {
- ex.printStackTrace();
- } finally {
- return rect;
- }
- }
- // Читает данные для Rectangle из текстового файла и создает на их основе экземпляр Rectangle,
- // имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
- public static void writeTraineeToTextFileOneLine(File file, Trainee trainee) {
- try(OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8")) {
- writer.write(trainee.getFirstName()+" "+trainee.getLastName()+" "+trainee.getRating());
- writer.flush();
- } catch (FileNotFoundException ex) {
- ex.printStackTrace();
- } catch (UnsupportedEncodingException ex) {
- ex.printStackTrace();
- } catch(IOException ex) {
- ex.printStackTrace();
- }
- }
- // Записывает Trainee в текстовый файл в одну строку в кодировке UTF-8, имя файла задается экземпляром класса File. Имя, фамилия и оценка в файле разделяются пробелами.
- public static Trainee readTraineeFromTextFileOneLine(File file) {
- Trainee trainee = null;
- try(BufferedReader br = new BufferedReader (new FileReader(file))) {
- String[] arrRect = br.readLine().split(" ");
- trainee = new Trainee(arrRect[0],arrRect[1],Integer.parseInt(arrRect[2]));
- } catch (IOException ex) {
- ex.printStackTrace();
- } finally {
- return trainee;
- }
- }
- // Читает данные для Trainee из текстового файла и создает на их основе экземпляр Trainee, имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
- public static void writeTraineeToTextFileThreeLines(File file, Trainee trainee) {
- try(OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8")) {
- writer.write(trainee.getFirstName()+"\n"+trainee.getLastName()+"\n"+trainee.getRating());
- writer.flush();
- } catch (FileNotFoundException ex) {
- ex.printStackTrace();
- } catch (UnsupportedEncodingException ex) {
- ex.printStackTrace();
- } catch(IOException ex) {
- ex.printStackTrace();
- }
- }
- // Записывает Trainee в текстовый файл в кодировке UTF-8, каждое поле в отдельной строке, имя файла задается экземпляром класса File.
- public static Trainee readTraineeFromTextFileThreeLines(File file) {
- Trainee trainee = null;
- try(BufferedReader br = new BufferedReader (new FileReader(file))) {
- trainee = new Trainee(br.readLine(),br.readLine(),Integer.parseInt(br.readLine()));
- } catch (IOException ex) {
- ex.printStackTrace();
- } finally {
- return trainee;
- }
- }
- // Читает данные для Trainee из текстового файла и создает на их основе экземпляр Trainee, имя файла задается экземпляром класса File. Предполагается, что данные в файл записаны в формате предыдущего упражнения.
- public static void serializeTraineeToBinaryFile(File file, Trainee trainee) {
- try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
- oos.writeObject(trainee);
- } catch (Exception ex){
- ex.printStackTrace();
- }
- }
- // Сериализует Trainee в двоичный файл, имя файла задается экземпляром класса File.
- public static Trainee deserializeTraineeFromBinaryFile(File file) {
- Trainee trainee = null;
- try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
- Trainee p=(Trainee) ois.readObject();
- } catch(Exception ex){
- ex.printStackTrace();
- } finally {
- return trainee;
- }
- }
- // Десериализует Trainee из двоичного файла, имя файла задается экземпляром класса File.
- // Предполагается, что данные в файл записаны в формате предыдущего упражнения.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement