Wednesday, 22 August 2012

5 ways to convert InputStream to String in Java


InputStream to String Conversion Example
Converting InputStream to String in Java has become very easy after introduction of Scanner class in Java 5 and due to development of several open source libraries like Apache commons IOUtils and Google Open source guava-libraries which provides excellent support to convert InputStream to String in Java program. we often need to convert InputStream to String  while working in Java for example if you are reading XML files from InputStream and later performing XSLT transformation on it or if InputStream is reading data from text file or text input Source and we either want to log  Strings in log file or want to operate on whole String. Before Java 5 you would have to write lots of boiler plate code to read String line by line or byte by byte depending upon whether you are using either BufferedReader or not but as I said since JDK 5 addedScanner for reading input, its fairly easy to convert InputStream into String.


Before Converting any InputStream or ByteStream into String don't forget to provide character encoding or charSet which tells Java Which characters to expect from those streams of bytes. in the absence of correct character encoding you might alter the output because same bytes can be used to represent different character in different encoding. Another thing to keep in mind is that if you don't provide character encoding,Default character encoding in Java will be used which can be specified from System property "file.encoding" or "UTF-8" if file.encoding is not specified. In this Java tutorial we will see 5 different example of converting InputStream to String in Java both by using standard JDK libraries and using open source libraries.

How to convert InputStream to String in Java – 5 Examples

here are different ways to convert InputStream to String in Java, first we will see most simple way of reading InputStream as String.

InputStream to String -  Using Java 5 Scanner
Convert InputStream to String in Java - 5 Example tutorialjava.util.Scanner has constructor which accept an InputStream, a character encoding and a delimiter to read String from InputStream. Here we have used delimiter as "\A" which is boundary match for beginning of  the input as declared in java.util.regex.Pattern and that's why Scanner is returning whole String form InputStream. I frequently use this technique to read input from user in Java usingSystem.in which is most common example of InputStream in Java, but as demonstrated here this can also be used to read text file in Java.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Java program example to demonstrate How to convert InputStream into String by using JDK
 * Scanner utility. This program will work Java 5 onwards as Scanner was added in Java 5.
 */
        
public class InputStreamTest {

    public static void main(String args[]) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String inputStreamString = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
        System.out.println(inputStreamString);
    }
}

Output:
This String is read from InputStream by changing InputStream to String in Java.

If you want to see how an incorrect character encoding completely changes the String just change the character encoding form "UTF-8" to "UTF-16" and you see Chinese(may be) characters instead of English.

Output:
?????????????!???????????!??????^(4)????????

Convert InputStream to String - Plain old JDK4 Example
If you still need to do it on plain old Java on JDK4 without including any additional dependency in your PATH and Classpath than here is quick example using BufferedReader in JavaRemember you can also do this by reading byte by byte from InputStream but that's very slow so consider using BufferedReader for better performance even if you code on JDK4 . For more performance tips see my post 4 JDBC performance tips in Java program. Let’s see example of converting InputStream to String using BufferedReader in Java.

/**
 * Java program to demonstrate How to read InputStream as String
 * using BufferedReader and StringBuilder in Java.
 * This is old and standard way of converting an InputStream into String in Java
 */

public static void main(String args[]) throws FileNotFoundExceptionUnsupportedEncodingExceptionIOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        String line = bufferedReader.readLine();
        while(line !null){
            inputStringBuilder.append(line);inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        System.out.println(inputStringBuilder.toString());

}
Output:
This String is read from InputStream by changing InputStream to String in Java.
second line


This is good plain old Java method of converting InputStream to String without adding any extra dependency but remember its converting \r to \n because we are reading line by line, which in most cases fine.

Read InputStream to String - Using Apache IOUtils library
As I said earlire there are many open source library in Java which makes coding lot more easier than any other language. Here is code example for How to convert InputStream to String in Java using Apache IOUtils

/**
 * Example of How to read InputStream into String by using Apache IOUtils library.
 * Nice and clean way of getting InputStream as String in Java
 */


FileInputStream fis = new FileInputStream("c:/sample.txt");
String StringFromInputStream = IOUtils.toString(fis, "UTF-8");
System.out.println(StringFromInputStream);

Isn't it a compact way of converting InputStream to String in Java, just one line of code and that does take care of character encoding as well..

InputStream to String - Using Google's guava-libraries
Google has open source its own set of Java libraries they use for Java development inside Google. it has lots of utility function and also complements Apache commons package. Here is a quick way of converting InputStream to String using Google libraries:

String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));

Regarding dependency, You need to include guava library i.e. guava-11.0.1.jar in your project classpath. here is full code example:

import com.google.common.io.CharStreams;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * How to convert InputStream into String in Java using Google's Guava library
 */

public class InputStreamToString{

    public static void main(String args[]) throws UnsupportedEncodingExceptionIOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));
        System.out.println(stringFromStream);
    }    
}

How to read InputStream into String with IOUtils.copy and StringWriter class
java.io.StringWriter is another convenient way of reading writing Strings and by using IOUtils.copy() you can copy contents form InputStream to reader, Here is a complete code example of reading InputStream as String using StringWriter:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;

/**
  * Java Program to demonstrate reading of InputStream as String
  * using StringWriter and Apache IOUtils
  */

public class InputStreamToStringConversion{

    public static void main(String args[]) throws FileNotFoundExceptionUnsupportedEncodingExceptionIOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringWriter writer = new StringWriter();
        String encoding = "UTF-8";
        IOUtils.copy(fis, writer, encoding);
        System.out.println(writer.toString());
    }
}

That's all on converting InputStream to String in Java by using standard core java library and by using open source Apache commons IOUtils and Google's guava libraries. Don't forget Character encoding when converting bytes to String which is case here also make a convenient choice as sometime adding additional library for one functionality is not the best option. let us know if you know any other way of convertingInputStream to String in Java.


Read more: http://javarevisited.blogspot.com/2012/08/convert-inputstream-to-string-java-example-tutorial.html#ixzz24GmqYHcR

How to get environment variables in Java- Example Tutorial

Environment variables in Java
There are two ways to get environment variable in Java, by using System properties or by using System.getEnv(). System properties provides only limited set of predefined environment variables like java.classpath, for retriving Java Classpath or java.username  to get User Id which is used to run Java program etc but a more robust and platform independent way of getting environment variable in Java program on the other hand Sytem.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if program relies on a particular environment variable. Sytem.getEnv() is overloaded method in Java API and if invoked without parameter it returns an unmodifiable String map which contains all environment variables and there values available to this Java process whileSystem.getEnv(String name) returns value of environment variable if exists or null. In our earlier posts we have seen How to get current directory in Java and  How to run shell command from Java program and in this Java tutorial we will see how to access environment variable in Java.

How to get environment variables in Java - Example

How to get value of environment variable in Java - example tutorialHere is a quick example on How to get environment variable in Java using System.getEnv() and System.getProperty(). Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return value of named environment variable like JAVA_HOME will return PATH of your JDK installation directory.

/**
 * Java program to demonstrate How to get value of environment variables in Java.
 * Don't confuse between System property and Environment variable and there is separate
 * way to get value of System property than environment variable in Java, as shown in this
 * example.
 *
 * @author Javin Paul
 */


public class EnvironmentVariableDemo { 

    public static void main(String args[]){
 
      //getting username using System.getProperty in Java
       String user = System.getProperty("user.name") ;
       System.out.println("Username using system property: "  + user);
 
     //getting username as environment variable in java, only works in windows
       String userWindows = System.getenv("USERNAME");
       System.out.println("Username using environment variable in windows : "  + userWindows);
 
   
     //name and value of all environment variable in Java  program
      Map<StringString> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName, env.get(envName));
        }

    }
   
}

Output:Username using system property: harry
Username using environment variable in windows : harry
USERPROFILE=C:\Documents and Settings\harry
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_20\
TEMP=C:\DOCUME~1\harry\LOCALS~1\Temp


Getting environment variable in Java – Things to remember
Java is platform independent language but there are many things which can make a Java program platform dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be bit careful while directly accessing environment variable inside Java program. Here are few points which is worth noting :

1) Use system properties if value of environment variable is available via system property e.g. Username which is available using "user.name" system property. If you access it using environment variable directly you may need to ask for different variable as it may be different in Windows  e.g. USERNAME and Unix as USER.

2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.

3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.

That's all on how to get environment variable in Java. Though you have convenient method like System.getEnv() which can return value of environment variable, its better to use System.getProperty()to get that value in a platform independent way, if that environment variable is available as system property in Java.

How to format String in Java – printf Example


String format and printf Example
How to format String in Java is most common problem developer encounter because classic System.out.println() doesn’t support formatting oString while printing on console. For those who doesn’t  know What is formatted String ? here is a simple definition,  Formatted String is a String which not only display contents but also display it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of need for modern GUI application and thankfully Java has good support for formatting String and all other types like IntegersDouble and DateHow to format a String in Java is never as easy as it has been since Java 1.5 which along-with front line features like GenericsEnumAutoboxing and Varargs also introduces several utility method to support rich formatting of String in Java. prior to Java 5 java programmer relies java.text API for all there formatting need but with Java 5 we have now two more convenient way to format String in Java. JDK 1.5 has added format() method in java.lang.String class and provided a printf() method in PrintStream class for printing formatted output in console. printf() method is similar to C programming language printf()method and allows programmer to print formatting string directly to console, which makes System.out.printf() better alternative of System.out.println() method. Both format() and printf()  are overloaded method to support Locale specific formatting.

By the way this is the third article about formatting in Java , earlier we have seeDecimal Format examples and DateFormat examples for formatting numbers and dates in Java.

How String.format() or printf() works in Java

Java String format Example printf String.format() and System.out.printf() both works similarly and if you see the signature of both method they also accepvariable arguments . Both take minimum two parameters, first of them is formatting instruction and other was actual String or anything which needs to be formatted. Java formatting instructions are both powerful and flexible and allows you to generate formatted String on many different format. Its worth to understand format of "formatting instruction" to take full benefit of String.format() method because this is the only tricky part of String formatting specially if you have not used printf() in past. I have seen developer struggle to understand the formatting behavior because of lack of knowledge of different formatting options available in Java.This is how we specify formatting instruction in Java :

String.format "%[argument number] [flags] [width] [.precision] type"

Now let's see what is meaning of each part of formatting instruction. "%" is a special character in formatted String and it denotes start of formatting instruction. String.format() can support multiple formatting instruction with multiple occurrence of "%" character in formatting instruction.

"argument number" is used to specify correct argument in case multiple arguments are available for formatting. "flags" is another special formatting instruction which is used to print String in some specific format for example you can use flag as "," to print comma on output. "width" formatting option denotes minimum number or character will be used in output but in case if number is larger than width then full number will be displayed but if its smaller in length then it will be be padded with zero. "precision" is using for print floating point formatted String, by using precision you can specify till how many decimal a floating point number will be displayed in formatted String. "type" is the only mandatory formatting option and must always comes last in format String also input String which needs to be formatted must be with same type specified in "type" parameter. for example you can not input a floating point number if you have specified "type" as decimal integer "%d", that will result in error. Now let's see an example of String format() method to understand these formatting option better:

format ( "%,6.2f"124.000)

In above example of  String.format() method flag is comma "," , width is 6 and precision is upto 2 decimal point and type is float.

String format Example in Java
In this section we will see different examples to format String in Java. We will see how we can format numbers and dates. Introduce decimal points and aligning number left or right etc. One of the common application of format() is to print leading zero in a number as shown in this Java program example:

/**
 * Java program to demonstrate How to format String in Java by using
 * format() method of String class and printf() method of OutputStream in Java.
 * String.format() is very powerful and not only can format String but numbers
 * and Date in Java
 *
 * @author Javin
 */

public class StringFormatExample{

    public static void main(String args[]){          
   
        //simple example of formatted string in Java
        //%d is used to format decimals like integers
        //position of argument is the order in which they appear in source String
          e.g here 40021 will replace first %d and 3000 will replace second %d.

        String formattedString = String.format("Order with OrdId : %d and Amount: %d is missing"400213000);       

      
 System.out.println(formattedString); 

 
        System.out.printf("Order with OrdId : %d  and Amount: %d is missing \n"400213000);
   
        //%s is used to denote String arguments in formatted String
        String str = String.format("Hello %s""Raj");
        System.out.println(str);
   
        //if argument is not convertible into specified data type than
 //Formatter will throw following java.util.IllegalFormatConversionException

        //e.g. specifying %d and passing 3.0
   
        //str = String.format("Number %d", 3.0);
   
//        Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
//      at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999)
//      at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2709)
//      at java.util.Formatter$FormatSpecifier.print(Formatter.java:2661)
//      at java.util.Formatter.format(Formatter.java:2433)
//      at java.util.Formatter.format(Formatter.java:2367)
//      at java.lang.String.format(String.java:2769)
   
        //common meta characters used in String.format() and
 //System.out.printf() method: %s - String , %d - decimal integer

        // %f - float  %tD - date as MM/dd/yy while %td is day %tm is month
 // and %ty is 2 digit year while %tY is four digit year

   
        //Formatting date in String format method - date in MM/dd/yy
        str = String.format("Today is %tD"new Date());
        System.out.println(str);
   
        Date today = new Date();
        System.out.printf("Date in dd/mm/yy format %td/%tm/%ty %n", today,today,today );
   
        // date as July 25, 2012, difference between %td and %te is that
 // %td use leading zero while %te doesn't
        System.out.printf("Today is %tB %te, %tY %n", today,today,today,today);
   
        //adding leading zero in numbers using String format,
 //%d is for decimal, 8 specify formatted number should be 8 digit and 0 specify use
        //leading zero, default is space, so if you don't specify leading
 // character space will be used.
        System.out.printf("Amount : %08d %n" , 221);
   
        //printing positive and negative number using String format
 //+ sign for positive, - for negative and %n is for new line

        System.out.printf("positive number : +%d %n"1534632142);
        System.out.printf("negative number : -%d %n"989899);
   
        //printing floating point number with System.format()
        System.out.printf("%f %n"Math.E);
   
        //3 digit after decimal point
        System.out.printf("%.3f %n"Math.E);
   
        //8 charcter in width and 3 digit after decimal point
        System.out.printf("%8.3f %n"Math.E);
   
        //adding comma into long numbers
        System.out.printf("Total %,d messages processed today"10000000);
    }


}

Output:
Order with OrdId : 40021  and Amount: 3000 is missing
Order with OrdId : 40021  and Amount: 3000 is missing
Hello Raj
Today is 07/25/12
Date in dd/mm/yy format 25/07/12
Today is July 252012
Amount : 00000221
positive number : +1534632142
negative number : -989899n
2.718282
2.718
   2.718
Total 10,000,000 messages processed today


Difference between the printf and format methods in Java

printf() and format()both methods are used to format String in Java and more or less similar. printf()is more close to C programming language because of identical name used in  C programming language, Anyone who has work in C previously can easily start with this printf() method also its look more as a replacement of System.out.println(). if you don't want to print just want a formatted string for any other purpose String format() method is a way to go. In summary you can say that printf()writes on stdout while format() return you a formatted string.

We have already seen String format examples with both format and printf method. In short formatting is easier in Java and it provides several classes like DateFormat, NumberFormat etc which can also be used to format Date and numbers.