Добавлены метода сохранения и загрузки хранилищ в MapsCollection

This commit is contained in:
Данила Мочалов 2022-11-19 16:11:28 +04:00
parent a9f39a20a9
commit 1d30c011aa
2 changed files with 77 additions and 5 deletions

View File

@ -1,5 +1,8 @@
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
public class MapWithSetLocomotivesGeneric public class MapWithSetLocomotivesGeneric
@ -189,6 +192,7 @@ public class MapWithSetLocomotivesGeneric
/// Загрузка списка из массива строк /// Загрузка списка из массива строк
public void LoadData(String[] records) public void LoadData(String[] records)
{ {
Collections.reverse(Arrays.asList(records));
for (var rec : records) for (var rec : records)
{ {
_setLocomotives.Insert((T)DrawningObjectLocomotive.Create(rec)); _setLocomotives.Insert((T)DrawningObjectLocomotive.Create(rec));

View File

@ -1,9 +1,10 @@
import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
public class MapsCollection { public class MapsCollection {
/// Словарь (хранилище) с картами /// Словарь (хранилище) с картами
final HashMap<String, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>> _mapStorages; final HashMap<String, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>> _mapStorages;
/// Возвращение списка названий карт /// Возвращение списка названий карт
public ArrayList<String> keys() { public ArrayList<String> keys() {
@ -13,10 +14,13 @@ public class MapsCollection {
private final int _pictureWidth; private final int _pictureWidth;
/// Высота окна отрисовки /// Высота окна отрисовки
private final int _pictureHeight; private final int _pictureHeight;
// Сепараторы
private final char separatorDict = '|';
private final char separatorData = ';';
/// Конструктор /// Конструктор
public MapsCollection(int pictureWidth, int pictureHeight) public MapsCollection(int pictureWidth, int pictureHeight)
{ {
_mapStorages = new HashMap<String, MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>>(); _mapStorages = new HashMap<String, MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth; _pictureWidth = pictureWidth;
_pictureHeight = pictureHeight; _pictureHeight = pictureHeight;
} }
@ -24,7 +28,7 @@ public class MapsCollection {
public void AddMap(String name, AbstractMap map) public void AddMap(String name, AbstractMap map)
{ {
// Логика для добавления // Логика для добавления
if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap>(_pictureWidth, _pictureHeight, map)); if (!_mapStorages.containsKey(name)) _mapStorages.put(name, new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
} }
/// Удаление карты /// Удаление карты
public void DelMap(String name) public void DelMap(String name)
@ -33,15 +37,79 @@ public class MapsCollection {
if (_mapStorages.containsKey(name)) _mapStorages.remove(name); if (_mapStorages.containsKey(name)) _mapStorages.remove(name);
} }
/// Доступ к парковке /// Доступ к парковке
public MapWithSetLocomotivesGeneric<DrawningObjectLocomotive, AbstractMap> Get(String ind) public MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap> Get(String ind)
{ {
// Логика получения объекта // Логика получения объекта
if (_mapStorages.containsKey(ind)) return _mapStorages.get(ind); if (_mapStorages.containsKey(ind)) return _mapStorages.get(ind);
return null; return null;
} }
// Доп.индексатор из задания // Доп.индексатор из задания
public DrawningObjectLocomotive Get (String name, int position) { public IDrawningObject Get (String name, int position) {
if (_mapStorages.containsKey(name)) return _mapStorages.get(name)._setLocomotives.Get(position); if (_mapStorages.containsKey(name)) return _mapStorages.get(name)._setLocomotives.Get(position);
else return null; else return null;
} }
/// Сохранение информации по локомотивам в хранилище в файл
public boolean SaveData(String filename)
{
File file = new File(filename);
if (file.exists())
{
file.delete();
}
try(BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
bw.write("MapsCollection\n");
for (var storage : _mapStorages.entrySet()) {
bw.write("" + storage.getKey() + separatorDict + storage.getValue().GetData(separatorDict, separatorData) + "\n");
}
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
return true;
}
/// Загрузка информации по локомотивам в депо из файла
public boolean LoadData(String filename)
{
File file = new File(filename);
if (!file.exists())
{
return false;
}
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String curLine = br.readLine();
if (!curLine.contains("MapsCollection")) {
return false;
}
_mapStorages.clear();
while ((curLine = br.readLine()) != null) {
var elems = curLine.split(Character.toString(separatorDict));
AbstractMap map = null;
switch (elems[1])
{ //TODO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
case "SimpleMap":
map = new SimpleMap();
break;
case "SpikeMap":
map = new SpikeMap();
break;
case "RailMap":
map = new RailMap();
break;
}
_mapStorages.put(elems[0], new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.get(elems[0]).LoadData(elems[2].split(Character.toString(separatorData)));
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return true;
}
} }