-
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 )
...
Can anyone help on this ????
Thank you in advance ...
-
I might be missing something here but dosn't InputStream accept byte[] in its read method?
InputStream thisInput=new InputStream();
thisInput.read(stringObjecttoConvert.getBytes());
then pass thisInput to whatever method requires an InputStream as a param
jolly
-
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);
}
-
couple of things i forgot to metion; my posted code never compiles, to prevent someone handing it is as homework..
and you need to replace the MYSTRING with the actual string you want to read the chars from (one of your 500)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|