Java File Transfer over Sockets: Sending and Receiving Byte Arrays
In Java, transferring files over sockets involves converting the file into byte arrays, sending them via the socket, and then converting the bytes back into a file at the receiving end. This article addresses an issue encountered by a Java developer in implementing this file transfer functionality.
Server-Side Issue
The server code appears to create an empty file upon receiving data from the client. To resolve this, the server should use a loop to read the data sent by the client in chunks, using a buffer to temporarily store the data. Once all data has been received, the server can write the complete file. The corrected server code is as follows:
<code class="java">byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = in.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); }</code>
Client-Side Issue
The client code initially sends an empty byte array to the server. To send the actual file content, the following code should be used:
<code class="java">FileInputStream is = new FileInputStream(file); byte[] bytes = new byte[(int) length]; is.read(bytes); out.write(bytes);</code>
Improved Code
With the aforementioned corrections, the full code for server and client is as follows:
Server:
<code class="java">... byte[] buffer = new byte[1024]; DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); FileOutputStream fos = new FileOutputStream("C:\test2.xml"); int bytesRead = 0; while ((bytesRead = in.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } fos.close(); ...</code>
Client:
<code class="java">... Socket socket = new Socket(host, 4444); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream())); File file = new File("C:\test.xml"); FileInputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { System.out.println("File is too large."); } byte[] bytes = new byte[(int) length]; is.read(bytes); out.write(bytes); ...</code>
The above is the detailed content of How to Correctly Transfer Files Over Sockets in Java?. For more information, please follow other related articles on the PHP Chinese website!