File Transfer over Sockets in Java
File transfer across sockets necessitates transforming files into byte arrays, transmitting them, and reconstituting them on the receiving end. This guide addresses the complexities encountered in this process.
Server-Side Receiving Logic
The server establishes a socket listener, accepts incoming connections, and initializes data streams for communication. The critical step is reading the received bytes and saving them to a local file:
<code class="java">byte[] bytes = new byte[1024]; in.read(bytes); FileOutputStream fos = new FileOutputStream("C:\test2.xml"); fos.write(bytes);</code>
The in.read(bytes) method retrieves the incoming data, while fos.write(bytes) writes it to the local file.
Client-Side Sending Logic
On the client side, the file is read into a byte array, and the data is then sent over the socket:
<code class="java">File file = new File("C:\test.xml"); long length = file.length(); byte[] bytes = new byte[(int) length]; // ... out.write(bytes);</code>
The out.write(bytes) method sends the converted file bytes to the server.
Stream Copying Improvement
However, using read and write methods directly can be inefficient. Instead, InputStream and OutputStream provide the transferTo method for faster data transfer:
<code class="java">int count; byte[] buffer = new byte[8192]; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); }</code>
This technique automates the byte copying process and significantly improves performance.
The above is the detailed content of How to Efficiently Transfer Files over Sockets in Java?. For more information, please follow other related articles on the PHP Chinese website!