0

I started creating a HTTP server application in java. when i tried to download a file from browser, the file size is incresed by 1 byte. and the file is not openning.

content-length : 12345 original size: 12345 downloaded size : 12346

                        ResHead resHead = new ResHead(StatusCode.OK);

                        String responseHeader = resHead
                                                .addContentTypeFromFile(file.getName())
                                                .addContentLength(file.length())
                                                .getResponseHeader();

                        os.write(responseHeader.getBytes());


                        FileInputStream fileInputStream = new FileInputStream(file);

                        BufferedInputStream in = 
                            new BufferedInputStream(fileInputStream);

                            OutputStream out = new BufferedOutputStream(os); // for writing

                        System.out.println(file.length());
                        byte[] buffer = new byte[1024 * 50];
                        int len = 0;
                        while ((len = in.read(buffer)) >= 0) {
                                out.write(buffer, 0, len);
                        }
                        fileInputStream.close();
                        os.flush();
nscube
  • 21
  • 1
  • 1
    Does this answer your question? [Why a downloaded file can get corrupted?](https://stackoverflow.com/questions/19309822/why-a-downloaded-file-can-get-corrupted) – Royce Nov 19 '19 at 14:47
  • 2
    Possible newline translation (from `"\n"` to `"\r\n"`)? Use some kind of comparison tool to find out where the difference is between the files, and what that single extra byte is (and check its surrounding bytes). – Some programmer dude Nov 19 '19 at 14:48
  • @Royce that is not a duplicate. – f1sh Nov 19 '19 at 14:50
  • You are supposed to flush `out`, not `os`. It would also probably be best to open `out` before you create the header, and use it rather than `os` throughout the program. – RealSkeptic Nov 19 '19 at 14:51
  • Wrap your streams (in and out) in `try-with-resource` and you wont have to worry about closing them. it will auto flush and close. – locus2k Nov 19 '19 at 14:53
  • Thank you. I change from `"\n\r"` to `"\r\n"`. And now it is working. – nscube Nov 19 '19 at 14:53

1 Answers1

0

I solved this problem by replacing "\n\r" to "\r\n". Thank you.

nscube
  • 21
  • 1