In this tutorials we are going to see how to convert InputStream to String using methods available in Java IO.
- Create project called JavaMisc.
- Create package called com.javatutorialscorner.io
- Create java class called InputStreamToString under com.javatutorialscorner.io package.
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 content read from input file
this is test file created by java tutorials corner
0 comments:
Post a Comment