Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
FileInputStream in = new FileInputStream("C:\\Users\\User_2\\Pictures\\19082012122.jpg");
           
           int c;
           String s = "";
           while((c = in.read()) != -1)
               s += c + " ";
Posted

A jpg file is a binary file, but if it wasn't you could use a StringBuilder[^]

Using String as a buffer for the input is inefficient, string really isn't meant for this.

You should determine the size of the file in bytes and use a byte[] array with the read[^] method.

Best regards
Espen Harlinn
 
Share this answer
 
In java all String instances are immutable. This means that once you created them you can not change their contents. Because of this your s += c + " "; statement does the following: Creates a new String object whose value is the the original string, c, and " " concatenated together then assign this new string to the s variable. s no longer references the old string so that will be garbage collected at some point. Depending on the optimization capabilities of the java compiler the old_s + c + " " expression might use an additional temporary string before creating the new value of s because first it adds old_s + c (this is the temp string), then it adds " " to the temp string. If you use StringBuilder it has an internal storage that allows you to manipulate your string data much more efficiently and you can create a String instance from its actual content at any point. Don't use StringBuffer instead of StringBuilder if you dont have to because the former contains thread synchronization so it is much slower! Apart from this, you should never store binary data in a string!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900