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:
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
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:
FileInputStream is = new FileInputStream(file);
byte[] bytes = new byte[(int) length];
is.read(bytes);
out.write(bytes);
Improved Code
With the aforementioned corrections, the full code for server and client is as follows:
Server:
...
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();
...
Client:
...
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);
...
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3