Finishing SerializeParser
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing

This commit is contained in:
Debucquoy Anthony 2023-03-25 17:18:47 +01:00
parent a70f658952
commit 746546fbfc
2 changed files with 27 additions and 20 deletions

View File

@ -58,4 +58,18 @@ public class Map extends Shape{
public ArrayList<Piece> getPieces() {
return pieces;
}
/**
* return a new Clean Map without any pieces on it for saving purpose
* @return a New Map Object without any pieces or saved data
*/
public Map getCleanedMap() {
try {
Map ret = (Map) this.clone();
ret.getPieces().clear();
return ret;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -3,37 +3,30 @@ package school_project.Parsers;
import school_project.Map;
import java.io.*;
import java.nio.file.Files;
public class SerializeParser implements FileParser{
@Override
public void saveLevel(File file, Map levelData, boolean save_data) throws IOException {
FileOutputStream fileStream = new FileOutputStream(file);
ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
objectStream.writeObject(levelData);
objectStream.close();
fileStream.close();
}
/**
* Check if the file is a text file
* @return true if it is a text File
*/
public static boolean isJsonFile(File file) throws IOException {
return Files.probeContentType(file.toPath()).equals("application/json");
}
@Override
public Map getLevel(File file, boolean saved_data) throws IOException {
// saved_data is ignored in this case because the file is serialized data and it already knows if should have saved_data or not at this point
FileInputStream fileStream = new FileInputStream(file);
ObjectInputStream objectStream = new ObjectInputStream(fileStream);
try {
return (Map) objectStream.readObject();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
throw new IOException("the serialized file format has not found any object in the file");
}
}
@Override
public void saveLevel(File file, Map levelData, boolean save_data) throws IOException {
FileOutputStream fileStream = new FileOutputStream(file);
ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
objectStream.writeObject(save_data ? levelData : levelData.getCleanedMap());
objectStream.close();
fileStream.close();
}
}