Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 213
bhushan23 Avatar asked Mar 01 '13 15:03

bhushan23


People also ask

What is a FileInputStream in Java?

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .


2 Answers

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();    } } 
like image 145
Arsen Alexanyan Avatar answered Sep 20 '22 08:09

Arsen Alexanyan


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();    } } 
like image 26
Aubin Avatar answered Sep 19 '22 08:09

Aubin