Java - InputStream read loop not closing when file has finished transferring

112 views Asked by At

I am trying emulate downloading/uploading. I am reading a file from a FileInputStream and send it over an OutputStream to an intermediary server which uses transferTo() to send the data over an OutputStream to the downloader (socket), where it is read from an InputStream and written to a file using FileOutputStream.

The file transfer is working but the loop that reads the bytes on the downloader side isn't detecting that the stream is finished. Why is this happening?

Code for uploader:

fis = new FileInputStream(transferFilePath);

byte[] dataBytes = new byte[1024];

                int nread;
                while ((nread = fis.read(dataBytes)) != -1) {
                    output.write(dataBytes,0, nread);
                    md.update(dataBytes, 0, nread);
                }

                output.flush();

Code on intermediary server:

OutputStream output;
            InputStream input;
            try {

                output = downloader.getOutputStream();
                input = sender.getInputStream();

                input.transferTo(output);

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

Code for uploader:

InputStream inStream = transferSocket.getInputStream();
                File targetFile = new File("targetFile");
                OutputStream outStream = new FileOutputStream(targetFile);

                byte[] dataBytes = new byte[1024];

                int nread;
                while ((nread = inStream.read(dataBytes)) != -1) {
                    outStream.write(dataBytes,0, nread);
                }

                System.out.println("Should hit here but does not :(");

Tried using output.flush and closing the output manually with output.close, not sure what else to try because im not sure what the issue is

SOLUTION: Issue was fixed by closing socket connection and not just the output/input streams

0

There are 0 answers