I am trying to send a file with Java TCP socket I/O Stream from Client to Server. I am using Data(Input|Output)Stream
in this process.
With every packet of file buffer, I want to send extra information (a Long
) as HEADER to every buffer
. I intend to use that info later for controlling I/O Streams.
Everything Works fine for the Following Codes (Without sending extra info (the long
)):
Client :
out
is DataOutputStream
from socket OutputStream
byte[] buffer = new byte[BUFFER_SIZE];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(data.getFile()));
out.writeUTF(file.getName());
out.writeLong(file.length());
int n;
long currentProgress = 0, totalProgress = file.length();
while ( (n =in.read(buffer, 0, buffer.length) ) != -1) {
// out.writeLong(123456);
out.write(buffer, 0, n);
out.flush();
currentProgress += n;
}
in.close();
Server : in
is DataInputStream
from socket InputStream
String fileName = in.readUTF();
long fileSize = in.readLong();
File file = new File(fileName);
try {
file.getParentFile().mkdirs();
} catch (NullPointerException ignore) {}
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[BUFFER_SIZE];
int n;
for (long sizeToRead = fileSize;
sizeToRead > 0; sizeToRead -= n) {
// in.readLong();
n = in.read(buffer, 0, (int) Math.min(buffer.length, sizeToRead));
if (n==-1) break;
bufferedOutputStream.write(buffer, 0, n);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
Everything just works fine now, but when I uncomment these two lines:
// out.writeLong(123456);
// in.readLong();
(Big) files get corrupted, I do not understand why this is happening as I am sending and receiving in order.
BUFFER_SIZE
is currently 512kb (512*1024)
[This is my first question in StackOverflow, sorry if I have represented my question poorly, Thank You]