If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

String to InputStream conversion

I have little problem with the conversion of java.lang.String to the java.io.InputStream.....

I have about 500 Strings which I would like to convert to InputStreams. Obviously if I go through
FileInputStream ,it would tie lot of resources since I will have to write each string to the File object first. for instantiating object of the FileInputStream(File f )

doesnt quite work like that.. inputstream is a source of characters, and it's read(byte[]) method will take characters from the source, and place them into the byte array provided.. so essentially, youre getting a byte array out of the string (using the string as a provider) and then overwriting it with the read() method of the inputstream (using inputstream also as a provider)

if you wish to use a String as a source of characters with a usage contract that is similar to an inputstream, the following code will be of help:

Code:

java.io.StringReader sr = new java.ioStringReader(MYSTRING);
char[] buffer = new char[1024];
for(int charsRead = sr.read(buffer); charsRead>-1; charsRead = sr.read(buffer)){
//do what you want now
//charsRead contains the number of chars that were read last time
//buffer contains the actual chars
//for example, to write up to charsRead chars from the buffer to a socket..
<java.net.Socket>.getOutputStream().write(buffer, 0, charsRead);
}