Marten
Marten

Reputation: 169

Java Download mp4 from url

I try to download a mp4 file from my Server and save it as a mp4 file. A file is created and has a size of 25 MB, but i can't play it with a video player.

Here is my code:

  HttpURLConnection con = (HttpURLConnection) new URL(serveradress).openConnection();
    con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; "
            + "Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like 
Gecko)"
            + " Chrome/53.0.2785.143 Safari/537.36");
    InputStream is = con.getInputStream();


    System.out.println(con.getResponseCode());

    String line = null;
    StringBuilder stringBuilder = new StringBuilder();

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

    while((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
    }

    is.close();

    String outVideo = stringBuilder.toString(); 


    File file = new File("C:\\Benutzer\\Admin\\Desktop\\video.mp4");        
    file.getParentFile().mkdirs();
    FileWriter writer = new FileWriter(file);
    writer.write(outVideo);
    writer.close();

    } catch(Exception ex) {
        ex.printStacktrace();
    }

Any help is really appreciated.

Upvotes: 0

Views: 4701

Answers (2)

Marten
Marten

Reputation: 169

Thanks a lot @A.Bergen with your tip i have found a solution and now it works.

        File file = new File("C:\\Benutzer\\Admin\\Desktop\\youtube.mp4");      
        file.getParentFile().mkdirs();

        BufferedInputStream bufferedInputStream = new  BufferedInputStream(new URL(decodedDownloadLink).openStream());
        FileOutputStream fileOutputStream = new FileOutputStream("C:/Benutzer/Admin/Desktop/youtube.mp4");


        int count=0;
        byte[] b = new byte[100];

        while((count = bufferedInputStream.read(b)) != -1) {                
            fileOutputStream.write(b, 0,count);
        }

Upvotes: 1

alikhtag
alikhtag

Reputation: 326

I am guessing the reason you cant play a saved video is that you are saving a string instead of byte[] data of the video.

Try using instead BufferedInputStream to read bytes And use FileOutputStream to save those bytes to the file

Dont use StringBuilder

Upvotes: 3

Related Questions