32

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
}
Aubin
14.9k11 gold badges67 silver badges88 bronze badges
asked Mar 1, 2013 at 15:47
5
  • 2
    what are you trying to achieve? naive is fis.toString(); Commented Mar 1, 2013 at 15:48
  • 2
    Well, there's always, fis.toString(), though that might probably not what you wanted. Why would you want to turn fis into a String? Commented Mar 1, 2013 at 15:49
  • you want the content of file input stream into string ? Commented Mar 1, 2013 at 15:49
  • 2
    Here's a good resource for you to start: docs.oracle.com/javase/tutorial/essential/io Commented Mar 1, 2013 at 15:49
  • Note: It's recommended to use the new NIO.2 File API instead of FileInputStream: docs.oracle.com/javase/tutorial/essential/io/file.html Commented Mar 1, 2013 at 16:05

6 Answers 6

31

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();
 }
}
answered Mar 1, 2013 at 15:53
8
  • 1
    May be :) I think he is not looking for the efficient way, he is just trying to learn Commented Mar 1, 2013 at 15:59
  • Actually, reading characters can be more efficient that reading lines which are strings, because a to make a String, you have top copy each of the characters in to the String, and that is only to return a String which is then copied to another String.... Commented Mar 1, 2013 at 16:01
  • @Aubin Why it is not efficient? Commented Mar 1, 2013 at 16:05
  • 1
    The native methods for moving a block of byte or characters can be faster than a loop that handles each character. However, what is more important is to look at whether there is needless extra search, converting, and copying of data, which accounts for more overhead than the character loop overhead. By the way, this answer is putting a byte into a character, which is a problem. Commented Mar 1, 2013 at 16:13
  • @AgilePro Why it is a problem converting byte into character? Commented Mar 1, 2013 at 16:18
25
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();
 }
}
answered Mar 1, 2013 at 15:49
5
  • Depending on the requirements of the Original Poster, perhaps needed the file encoding and line separator (or read as it appears in the file). Commented Mar 1, 2013 at 16:03
  • Yes, you're right but when reading stream to RAM we may accept the line terminator will be normalized into \n (assumption to debate) Commented Mar 1, 2013 at 16:06
  • The close should happen in a finally block, or better in a try-with-resource block. Commented Mar 1, 2013 at 16:06
  • 2
    You need to specify the character encoding. You can not assume that the platform default encoding will be correct. Commented Mar 1, 2013 at 16:10
  • I'm using file as a parameter to this function and if a condition satisfies then i have to print whole path of a file that's why i took fileinputstream as a parameter.... Commented Mar 7, 2013 at 15:31
16

Using Apache commons IOUtils function

import org.apache.commons.io.IOUtils;
InputStream inStream = new FileInputStream("filename.txt");
String body = IOUtils.toString(inStream, StandardCharsets.UTF_8.name()); 
answered Feb 21, 2018 at 22:02
1
  • This won't work in all cases as encoding could be different from UTF_8 Commented Aug 25, 2019 at 10:02
3

Don't make the mistake of relying upon or needlessly converting/losing endline characters. Do it character by character. Don't forget to use the proper character encoding to interpres the stream.

public String getFileContent( FileInputStream fis ) {
 StringBuilder sb = new StringBuilder();
 Reader r = new InputStreamReader(fis, "UTF-8"); //or whatever encoding
 int ch = r.read();
 while(ch >= 0) {
 sb.append(ch);
 ch = r.read();
 }
 return sb.toString();
}

If you want to make this a little more efficient, you can use arrays of characters instead, but to be honest, looping over the characters can be still quite fast.

public String getFileContent( FileInputStream fis ) {
 StringBuilder sb = new StringBuilder();
 Reader r = new InputStreamReader(fis, "UTF-8"); //or whatever encoding
 char[] buf = new char[1024];
 int amt = r.read(buf);
 while(amt > 0) {
 sb.append(buf, 0, amt);
 amt = r.read(buf);
 }
 return sb.toString();
}
answered Mar 1, 2013 at 15:54
4
  • Actually, there is good reason to believe it is more efficient than the code that is scanning for, and manipulating, the end of line characters, then copying that into a string for return. Character by character efficiently works with the native content of the stream. Commented Mar 1, 2013 at 15:57
  • sorry, forgot the Reader to convert bytes to chars. Commented Mar 1, 2013 at 16:03
  • 2
    You can not declare a variable in the while expression part. And the read of a Reader returns int, not char. Commented Mar 1, 2013 at 16:07
  • Yes, I actually prefer to keep the declaration out of the block condition, even though it means you have two lines with read statements. I have changed it thus. Commented Mar 1, 2013 at 16:15
1

From an answer I edited here:

static String convertStreamToString(java.io.InputStream is) {
 if (is == null) {
 return "";
 }
 java.util.Scanner s = new java.util.Scanner(is);
 s.useDelimiter("\\A");
 String streamString = s.hasNext() ? s.next() : "";
 s.close();
 return streamString;
}

This avoids all errors and works well.

answered Aug 29, 2017 at 16:41
1

Use following code ---->

try {
 FileInputStream fis=new FileInputStream("filename.txt");
 int i=0; 
 while((i = fis.read()) !=-1 ) { // to reach until the laste bytecode -1
 System.out.print((char)i); /* For converting each bytecode into character */ 
 }
 fis.close();
} catch(Exception ex) {
 System.out.println(ex); 
}
Thomas Fritsch
10.2k33 gold badges41 silver badges49 bronze badges
answered Nov 6, 2017 at 18:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.