Quantcast
Channel: How do I create a Java string from the contents of a file? - Stack Overflow
Viewing all articles
Browse latest Browse all 36

Answer by Henry for How do I create a Java string from the contents of a file?

$
0
0

Be aware when using fileInputStream.available() the returned integer does not have to represent the actual file size, but rather the guessed amount of bytes the system should be able to read from the stream without blocking IO. A safe and simple way could look like this

public String readStringFromInputStream(FileInputStream fileInputStream) {    StringBuffer stringBuffer = new StringBuffer();    try {        byte[] buffer;        while (fileInputStream.available() > 0) {            buffer = new byte[fileInputStream.available()];            fileInputStream.read(buffer);            stringBuffer.append(new String(buffer, "ISO-8859-1"));        }    } catch (FileNotFoundException e) {    } catch (IOException e) { }    return stringBuffer.toString();}

It should be considered that this approach is not suitable for multi-byte character encodings like UTF-8.


Viewing all articles
Browse latest Browse all 36

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>