R. Völker R. Völker - 1 year ago 67
Java Question

Strange behaviour of InputStream / OutputStream in Socket

As always I'm having trouble with Streams and Sockets.

Here is my Code:


bitOut.write((f.getName() + "\n").getBytes());
//System.out.println(f.length()); // <- This is the odd part.
bitOut.write((int) f.length());

fileIn = new FileInputStream(f);
byte buffer[] = new byte[BUFFER_SIZE];
int len;
while ((len = fileIn.read(buffer)) != -1) {
bitOut.write(buffer, 0, len);


file = sc.nextLine();
int fileSize = bitIn.read(); // <- Here is my error!
System.out.println(file + ", " + fileSize);

fileOut = new FileOutputStream(folder + file);
byte buffer[] = new byte[BUFFER_SIZE];
int len;
while (fileSize > 0 && (len = bitIn.read(buffer)) != -1) {
fileOut.write(buffer, 0, len);
fileSize -= len;

If I uncomment the
in the client code, the server is always getting the right value in
. But if I leave it commented,
is often a byte from the data which should be sent after
. On the one hand it's funny because almost only if I print out the file size in the client, I receive the right result on the server. On the other hand I got no clue how to fix it...

Answer Source

Ok I solved it. It was something with the Scanner, whose method nextLine() swallowed the byte I was sending after the file name. Now I'm just using the normal InputStream and OutputStream.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download