Java – Convert String to InputStream

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamExample {

	public static void main(String[] args) throws IOException {
		String str = "This is a String ~ GoGoGo";

		// convert String into InputStream
		InputStream is = new ByteArrayInputStream(str.getBytes());

		// read it with BufferedReader
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}

		br.close();
	}

}

Java – Convert InputStream to String

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToStringExample {

	public static void main(String[] args) throws IOException {
		//intilize an InputStream
		InputStream is = new ByteArrayInputStream("file content".getBytes());

		//read it with BufferedReader
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		StringBuilder sb = new StringBuilder();

		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}

		System.out.println(sb.toString());

		br.close();
	}

}

Java – Save Web Page to a File

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.swing.text.html.parser.DTD;

public class MainClass {
  public static void main(String[] args) {
    try {
      URL u = new URL("http://www.insecure.in");
      OutputStream out = new FileOutputStream("test.htm");
      InputStream in = u.openStream();
      DTD html = DTD.getDTD("html");
      System.out.println(html.getName());
      in.close();
      out.flush();
      out.close();
    } catch (Exception e) {
      System.err.println("Usage: java PageSaver url local_file");
    }
  }
}