Getting Text and Images from The Web with Java
I used this code to get images and text from the web. First an image:
public static BufferedImage getImage(String urlString)throws Exception {
// construct URL
URL url = new URL(urlString);
// get AWT image
Image image = Toolkit.getDefaultToolkit().getImage(url);
// cast to BufferedImage
return ImageUtils.toBufferedImage(image);
}
Now to return all text as a String:
public static String getText(String urlString) throws Exception {
// construct url
URL url = new URL(urlString);
// create input buffer for reading
BufferedReader in = new BufferedReader(new InputStreamReader(url
.openStream()));
// temp string
String str;
// create buffer to put information in
StringBuffer buffer = new StringBuffer();
// read until end of file
while ((str = in.readLine()) != null) {
// since reading line add line feed.
buffer.append(str+"\n");
}
// close buffer
in.close();
// return as string
return buffer.toString();
}
Comments
No comments yet.
Leave a comment