Search code examples
javafileinputstream

How to convert FileInputStream into string in java?


In my java project, I'm passing FileInputStream to a function, I need to convert (typecast FileInputStream to string), How to do it.??

public static void checkfor(FileInputStream fis) {
   String a=new String;
   a=fis         //how to do convert fileInputStream into string
   print string here
}

Solution

  • You can't directly convert it to string. You should implement something like this Add this code to your method

        //Commented this out because this is not the efficient way to achieve that
        //StringBuilder builder = new StringBuilder();
        //int ch;
        //while((ch = fis.read()) != -1){
        //  builder.append((char)ch);
        //}
        //          
        //System.out.println(builder.toString());
    

    Use Aubin's solution:

    public static String getFileContent(
       FileInputStream fis,
       String          encoding ) throws IOException
     {
       try( BufferedReader br =
               new BufferedReader( new InputStreamReader(fis, encoding )))
       {
          StringBuilder sb = new StringBuilder();
          String line;
          while(( line = br.readLine()) != null ) {
             sb.append( line );
             sb.append( '\n' );
          }
          return sb.toString();
       }
    }