Archives: String

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 – Generate Random alpha-numeric String

The code below show you how to use the apache commons RandomStringUtils class to generate some random string data.

Output:

random = 2377316738997278218735578855577798247976319451877477254850564896
random = wwqbLxlRynIdptAoxuSIfbABRoOFHLyKaFEscrUoBQjAHPOkcIqfHuMnhXVzaLCf
random = 6nQ0PJf<#VgIi=’&d*Ru#i_exMoHXb
random = ZGbelXYEiLrlLBXKroCIDJPrevZPIGkD

Java – Use String in Switch Statement

Starting from Java 7 release you can now use a string in the switch statement. On the previous version we can only use number or enum in the switch statement. The code below give you a simple example on it.