public class XMLToString implements StreamTransformation { public void setParameter(Map arg0) {} public void execute(InputStream arg0, OutputStream arg1) throws StreamTransformationException { try { DataInputStream dataInputStream = new DataInputStream(arg0); StringBuffer sbr = new StringBuffer(); String str = null; while ((str = dataInputStream.readUTF()) != null) { String str1 = str.trim(); sbr.append(str1); String string = new String(sbr);
//package com.xi.javamapping; import java.io.DataInputStream; //import java.io.File; //import java.io.FileInputStream; //import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map;
public void setParameter(Map arg0) {} public void execute(InputStream arg0, OutputStream arg1) throws StreamTransformationException { try { DataInputStream dataInputStream = new DataInputStream(arg0); StringBuffer sbr = new StringBuffer(); String str = null; while ((str = dataInputStream.readUTF()) != null) { String str1 = str.trim(); sbr.append(str1); String string = new String(sbr); byte[] b = string.getBytes(); arg1.write(b); } } catch (IOException e) { e.printStackTrace(); } } }
Since class InputStream is super class of the FileInputStream so we can store file into InputStream by taking the file through FileInputStream. The read() method of an InputStream class contains the byte value and returns an int. If the read() method returns -1, there is no more data to read in the stream. This value is stored into the StringBuffer as a string which will then converted into string. Here is the code:
import java.io.*; public class ConvertInputStreamToString { public static void main(String[] args) throws IOException { InputStream is = new FileInputStream("C:/file.txt"); StringBuffer buffer = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = is.read(b)) != -1;) { buffer.append(new String(b, 0, n)); } String str = buffer.toString(); System.out.println(str); } }