Tuesday, 1 October 2013

Convert InputStream to String using Java IO


In this tutorials we are going to see how to convert InputStream to String using methods available in Java IO.
  1. Create project called JavaMisc.
  2. Create package called com.javatutorialscorner.io
  3. Create java class called InputStreamToString under com.javatutorialscorner.io package.
InputStreamToString.java
package com.javatutorialscorner.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToString {

/**
* @param args
*/
public static void main(String[] args) {
InputStream is = null;

try {
is = new FileInputStream(new File(
"C:\\jtc\\javatutorialscorner.txt"));
String contentInFile = toString(is);
System.out.println(contentInFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private static String toString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = null;
String templine = "";

try {
sb = new StringBuilder();

br = new BufferedReader(new InputStreamReader(is));
while ((templine = br.readLine()) != null) {
sb.append(templine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return sb.toString();
}
}


Now run the program see the following output in console.

this is test file created by java tutorials corner

This content read from input file

0 comments

Post a Comment