I am new to the concept of working with streams and with files in Java.
I'm writing a piece of code, I have a very simple server that is listening for an incoming file.
Then I have a handler that deals with the incoming file.
Now, here is the code (stripped of try/catch blocks)
ObjectInputStream in;
in = new ObjectInputStream(new BufferedInputStream(
clientSocket.getInputStream()));
File f = new File(fileName);
int byteCount = in.readInt();
byte[] fileArray = (byte[]) in.readObject();
Files.write(f.toPath(), fileArray);
There comes an IOException when the program hits the ``byte[] fileArray = (byte[]) in.readObject();line. And - to be sure, theint byteCount` shows the correct number of bytes, the filename is also correct...
Stacktrace looks like this:
java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1304)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at com.fileservice.util.ClientHandlerRunnable.run(ClientHandlerRunnable.java:85)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Code of the client sending the file:
Socket socket = new Socket(data.getIp(), data.getTcpPort());
FileInputStream fis = null;
BufferedInputStream bis = null;
// OutputStream os = null;
// send file
File myFile = new File(data.getFileName());
String test = myFile.getAbsolutePath();
byte[] mybytearray = new byte[(int) myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
ObjectOutputStream os = new ObjectOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
os.flush();
System.out.println("Sending " + data.getFileName() + "("
+ mybytearray.length + " bytes)");
if (os != null) {
os.writeInt(mybytearray.length);
os.write(mybytearray, 0, mybytearray.length);
os.flush();
System.out.println("Done.");
}
if (bis != null) {
bis.close();
}
if (os != null) {
os.close();
}
if (socket != null) {
socket.close();
}