Url to File in Android

Viewed 47

I have an url. It is a direct link to the video. How to convert it to the File?

I found a solution how to convert an image

            Bitmap bitmap = null;
            InputStream input = new URL(imgUrl).openStream();
            bitmap = BitmapFactory.decodeStream(input);
            File file = new File(getCacheDir(), "1");
            file.createNewFile();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
            byte[] bitmapdata = bos.toByteArray();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();

But I can't find how to convert a video?

1 Answers

To convert direct video link to File you need implement this code below.

            InputStream input = new URL(videoUrl).openStream();
            File file = new File(getCacheDir(), "1");
            try (OutputStream outputStream = new FileOutputStream(file)) {
                IOUtils.copy(input, outputStream);
            } catch (FileNotFoundException e) {

            } catch (IOException e) {

            }

And you need to connect this dependency implementation 'commons-io:commons-io:2.6' for IOUtils class.

This approach will work with any file types (jpg, png, mp4, avi, pdf, webp, doc and so on). Happy coding.

Related