问题
This is a method with System.in and System.out using for write and read some object
PrintStream out = new PrintStream(System.out);
Transit.outputTransport(Parking, out);
System.out.println(Parking.toString());
out.close();
InputStream in = new BufferedInputStream(System.in);
Transport forOutNew = Transit.inputTransport(in);
System.out.println(forOutNew.toString());
in.close();
Every time, System.out.println(forOutNew.toString()); prints null . How can I fix the problem?
Given below is the original code which I changed to the one mentioned above:
OutputStream os = new FileOutputStream("out.txt");
Transit.outputTransport(Parking, os); - byte string of object information to file
os.close();
InputStream is = new FileInputStream("out.txt");
System.out.println(Parking.toString());
Transport forOut = Transit.inputTransport(is); - read byte string and create new object in method
is.close();
System.out.println(forOut.toString());
System.out.println();
Transit methods
public static void outputTransport (Transport v, OutputStream out) {
try (DataOutputStream output = new DataOutputStream(out))
{
if (v instanceof Cars){
output.write(0);
} else if (v instanceof Motos){
output.write(1);
} else {
throw new IOException();
}
output.write(((v.getType()).getBytes()).length);
output.write((v.getType()).getBytes());
output.write(v.getNumber());
String[] mas2 = v.getAllModels();
double[] mas1 = v.getAllPrices();
for (int i=0; i < v.getNumber(); i++)
{
output.writeDouble(mas1[i]);
output.writeInt(((mas2[i]).getBytes()).length);
output.write((mas2[i]).getBytes());
}
System.out.println();
System.out.println("Successful");
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static Transport inputTransport (InputStream in) { // input stream
try (DataInputStream input = new DataInputStream(in)) {
int flag = input.readByte();
if ((flag == 0) || (flag == 1)) { // cars = 0, motos = 1
int n = input.readByte();
int b;
String s = new String(input.readNBytes(n));
if (flag == 0) {
n = input.readByte();
Factory newObject = new CreatorFactory(flag, s, n);
Transport forOut = newObject.createTransport();
for (int i = 0; i < n; i++) {
forOut.changePrice("default"+i, input.readDouble());
b = input.readInt();
s = new String(input.readNBytes(b));
forOut.changeModel("default"+i, s);
}
return forOut;
} else if (flag == 1) {
Factory newObject = new CreatorFactory(flag, s);
Transport forOut = newObject.createTransport();
n = input.readByte();
for (int i = 0; i < n; i++) {
forOut.addModel("default", input.readDouble());
b = input.readInt();
s = new String(input.readNBytes(b));
forOut.changeModel("default", s);
}
return forOut;
}
} else {
throw new IOException();
}
}
catch(IOException | NoSuchModelNameException | DuplicateModelNameException e){
System.out.println(e.getMessage());
}
return null;
}
来源:https://stackoverflow.com/questions/60098656/fix-the-prolem-with-using-system-in-out-for-read-write-objects-in-by-file