JAVATM MASTER

readURL Method

Back to Table of Contents

This page includes in a way to read in a byte array from a URL, such as an image on a remote server. Basically, you create a ByteArrayOutputStream to hold the byte array, and a StringBuilder to hold any errors, and then you send both as parameters to the static performGet() method. if it returns true, you evaluate the ByteArrayOutputStream. If it returns false, you evaluate the StringBuilder.

package org.luxor.util;

import java.io.*;
import java.net.*;
import java.util.*;

public class NetMaster {

	
	public static boolean performGet(String urlString, 
			ByteArrayOutputStream resultBuf, 
			StringBuilder errBuf){
		InputStream in = null;
		try{
			URL url = new URL(urlString);
			byte[] buf = new byte[1024];
			int read = 0;
			in = url.openStream();
			while ((read = in.read(buf)) > -1){
				resultBuf.write(buf, 0, read);
			}
			return true;
		}
		catch(Exception ex){
			errBuf.append("NetMaster.performGet() " +
				"url was: "+urlString+" ex = "+ex);
			return false;
		}
		finally{
			close(in);
		}
	}
	public static void close(InputStream in){
		try{
			if (in != null) in.close();
		}
		catch(Exception ex){}
	}
	public static void close(OutputStream out){
		try{
			if (out != null) out.close();
		}
		catch(Exception ex){}
	}
	
	public static void main(String[] args){
		if (args.length < 1){
			System.out.println("Usage: java NetMaster url.toread.com");
			return;
		}
		String urlString = args[0];
		ByteArrayOutputStream resultBuf = new ByteArrayOutputStream();
		StringBuilder errBuf = new StringBuilder();
		boolean success = performGet(urlString, resultBuf, errBuf);
		if (success){
			System.out.println("Success: \r\n"+resultBuf);
		}
		else{
			System.out.println("Failure: \r\n"+errBuf);
		}
	}
}

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*