How to convert/read an input stream into a string in java?

Java 8Object Oriented ProgrammingProgramming

Java provides FileInputStream class for reading data from a file. This class provides read() method to read contents of a file character by character. Create a StringBuffer object and append character by character to it using the append() method. Finally, convert the contents of StringBuffer object to String using toString() method.

Example

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class StreamToString {
   public static void main(String args[]) throws IOException {
      File file = new File("da");
      FileInputStream fis = new FileInputStream(file);
      int size=fis.available();
      StringBuffer buffer = new StringBuffer();
        
      for(int i = 0; i< size; i++) {
         buffer.append((char)fis.read());
      }
      System.out.println(buffer.toString());
   }
}

Output

Hi how are you
raja
Published on 12-Jan-2018 05:01:34
Advertisements