I'm trying to read a file from an FTP server accessed with the FTPClient class from the Apache Commons library, but method to get a file retrieveFile(remoteFileName, OutputStream)
needs an OutputStream. I'm trying to get the object without first writing the file to the disk. Is there any way I can get the ObjectInputStream to read from an OutputStream? Or some other way that I haven't thought of yet?
EDIT: I've tried two ways:
public class FTPObjectReader
{
public static Object read()
{
try
{
FTPClient ftp = new FTPClient();
// Connect and stuff
// Way one
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ftp.retrieveFile("Data.dat", baos);
baos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream = new ObjectInputStream(bais);
Object o = ois.readObject();
// Way two
ObjectInputStream ois = new ObjectInputStream(ftp.retrieveFileStream("Data.dat"));
Object o = ois.readObject();
}
}
}
Stack trace:
java.io.StreamCorruptedException: invalid type code: 0A
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readArray(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.microgodrad.dev.Net.FTPObjectReader(FTPObjectReader.java:14)
at com.microgodrad.dev.Net.main(Net.java:162) // File that calls this function
Use a
ByteArrayOutputStream
, then when it's closed wrap its byte array in aByteArrayInputStream
and wrap that in anObjectInputStream.