Refactor CSV and Net loading to use InputStream for better flexibility

This commit is contained in:
2025-02-03 12:57:17 +01:00
parent 214705b675
commit bd61042573
6 changed files with 197 additions and 121 deletions

View File

@@ -3,6 +3,8 @@ package net.berack.upo.valpre.sim;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -250,15 +252,29 @@ public final class Net {
*
* @param file the file to load
* @return a new Net object
* @throws KryoException if the file saved is not a net
* @throws FileNotFoundException if the file is not found
* @throws KryoException if the file saved is not a net
* @throws IOException if the file is not found
*/
public static Net load(String file) throws KryoException, FileNotFoundException {
public static Net load(String file) throws KryoException, IOException {
try (var stream = new FileInputStream(file)) {
return Net.load(stream);
}
}
/**
* Load the net from the stream passed as input.
* The net will be the same as the one saved.
*
* @param stream the input stream to read
* @return a new Net object
* @throws KryoException if the file saved is not a net
*/
public static Net load(InputStream stream) throws KryoException {
var kryo = new Kryo();
kryo.setRegistrationRequired(false);
kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
try (var in = new Input(new FileInputStream(file))) {
try (var in = new Input(stream)) {
return (Net) kryo.readClassAndObject(in);
}
}

View File

@@ -1,8 +1,9 @@
package net.berack.upo.valpre.sim.stats;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -59,8 +60,20 @@ public class CsvResult {
* @throws IOException if anything happens while reading the file
*/
public Result[] loadResults() throws IOException {
try (var stream = new FileInputStream(this.file)) {
return CsvResult.loadResults(stream);
}
}
/**
* Load the results from the CSV stream.
*
* @param input the input stream to read
* @return the results loaded from the stream
*/
public static Result[] loadResults(InputStream input) {
var results = new ArrayList<Result>();
try (var scan = new Scanner(new File(this.file))) {
try (var scan = new Scanner(input)) {
var _ = scan.nextLine();
var nodes = new HashMap<String, Statistics>();