Archives: InputStream

Java – Convert String to InputStream

[code lang=”java”]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();
}

}[/code]


Java – Convert InputStream to String

[code lang=”java”]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();
}

}[/code]


Java – Save Web Page to a File