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 }
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 .
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(); } }
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With