-1

I'm working on a Java file downloader, so I just downloaded a video file with app and without app, so I saw file-size differences between that files. And I couldn't open the file which I downloaded by using my Java app. When I open them using Notepad++, I saw randomly generated symbols inside. What am I doing so wrong?

https://i.stack.imgur.com/LYDVm.png - here, as you can see randomly generated question marks there. https://i.stack.imgur.com/0rpSm.png - but in the original file, they doesn't exist. https://i.stack.imgur.com/5XC8q.png - here's the file sizes, I just placed "+" for the generated file.

Here's my code:

        String currentRange = "bytes=0-"+num*13107200;
        System.out.println(num + " is executing");
        URL file = new URL(url);
        FileOutputStream stream = new FileOutputStream("tmp"+num+".mp4"); 
        HttpURLConnection urlConnection = (HttpURLConnection) file.openConnection();
        urlConnection.setRequestProperty("Range", currentRange);
        urlConnection.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                urlConnection.getInputStream()));
        String inputLine;

        final PrintStream printStream = new PrintStream(stream);
        while ((inputLine = in.readLine()) != null)
            printStream.println(inputLine);
        in.close();
        printStream.close();
Walker
  • 131
  • 2
  • 16
  • 3
    Don't use Readers/Writers/PrintStreams for processing binary files, those are for text-data only. Use the raw streams. – piet.t Jul 05 '16 at 12:53
  • 4
    An mp4 file is a binary file. You can't expect seeing readable text if you open one with a text editor. And since it's binary, you should not use a Reader, which allows reading text, to download it. Use an InputStream. Note that since you just want to download files as is, that applies to any file, including text files. – JB Nizet Jul 05 '16 at 12:53
  • 1
    ``readLine()`` splits the data at each linebreak. Don't do that, you are reading raw binary data. And why do you open a video file with notepad++ and are surprised to see "randomly generated symbols"? What else did you expect? – f1sh Jul 05 '16 at 12:55
  • @f1sh I just wanted to see the difference between two files. – Walker Jul 05 '16 at 12:59

1 Answers1

0

I solved by using this code, thanks to this question: Reading binary file from URLConnection and @piet.t

InputStream input = urlConnection.getInputStream();
            byte[] buffer = new byte[4096];
            int n = - 1;
            while ( (n = input.read(buffer)) != -1) 
            {
                stream.write(buffer, 0, n);
            }
Community
  • 1
  • 1
Walker
  • 131
  • 2
  • 16