Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static byte[] fetchUrlToByte(String urlStr) {

        try {
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            InputStream is = urlConnection.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;

            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            return baos.toByteArray();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}