I'm trying to build a simple file transfer program that transfers a file from a server to a client. I gave it a try myself by simply writing the file to an ObjectOutputStream. This didn't work. I did some research and I found a whole swath of solutions that utilize a byte[] in which the contents of the file is written to that array and written to a OutputStream. Unfortunately none of the writers explain the code very well. I was curious if someone could explain to me why a byte[] is needed to read the file as opposed to my solution or even just reading the contents of the file into a String and sending that. What is it about a file and streams that require a solution like this? Thanks for any help.
File Transfer over Socket
java;sockets;files
A stream is simply a sequence of objects. If you are attempting to stream a file of unknown type, i.e. you are simply pushing raw data and not interpreting its contents, the usual representation is a byte stream.In Java, object streams are designed to send Objects. Even if you send a byte array, it will send an array object, not a sequence of bytes. They use serialization to send more complex objects which includes metadata.It sounds like you simply want the sequence of bytes that constitute the file contents.There are several ways to make this work, using either old-school sockets and streams or NIO. I suggest starting with the old way so you understand how everything works, then moving on to NIO (which is generally just an abstraction of lower level primitives anyway).Your server should open a ServerSocket, and the client should connect to the server. On the server you open an output stream from the socket, while the client opens an input stream. Note that the socket interface uses the interfaces, not anything like object streams. If you want different streams, you will need to wrap them.I suggest wrapping each in a buffered input or output stream, and sending the bytes across using that. The key here is that both ends of the stream need to use the same stream abstraction. If one end uses an object stream and the other does not, it will not work. By requesting streams from the sockets, it will work: they return private implementations that wrap the socket and are compatible.Once you understand how all the parts fit together, I suggest moving up to NIO which makes this a lot easier, but hides important details that it appears you need to learn about before you can safely abstract them away.