How do I turn a String into a InputStreamReader in java? - java

How can I transform a String value into an InputStreamReader?

ByteArrayInputStream also does the trick:
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Then convert to reader:
InputStreamReader reader = new InputStreamReader(is);

I also found the apache commons IOUtils class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

Does it have to be specifically an InputStreamReader? How about using StringReader?
Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).

Same question as #Dan - why not StringReader ?
If it has to be InputStreamReader, then:
String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);

Are you trying to get a) Reader functionality out of InputStreamReader, or b) InputStream functionality out of InputStreamReader? You won't get b). InputStreamReader is not an InputStream.
The purpose of InputStreamReader is to take an InputStream - a source of bytes - and decode the bytes to chars in the form of a Reader. You already have your data as chars (your original String). Encoding your String into bytes and decoding the bytes back to chars would be a redundant operation.
If you are trying to get a Reader out of your source, use StringReader.
If you are trying to get an InputStream (which only gives you bytes), use apache commons IOUtils.toInputStream(..) as suggested by other answers here.

You can try Cactoos:
InputStream stream = new InputStreamOf(str);
Then, if you need a Reader:
Reader reader = new ReaderOf(stream);

Related

Can one write to a wrapped Stream in java?

I'm writing a java server for an assignment, and I have observed some strange behaviour when I write both into a wrapped stream and a wrapper stream, can this cause any problems ? As far as I see, it can, but how ? Pls enlighten me.
as an example:
OutputStream os = new OutputStream(...);
PrintWriter pw = new PrintWriter(os);
And I want to write both in the PrintWriter, and the OutputStream.
To transfer from byte-based stream to character-based stream, you need to use OutputStreamWriter:
An OutputStreamWriter is a bridge from character streams to byte streams.
So that would be:
OutputStream os = ...
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
PrintWriter pw = new PrintWriter(osw);
I think the problem is that you need to specify the encoding, since the constructor PrintWriter(OutputStream out) uses the default encoding which might not be correct for your data input:
OutputStream os = ...
PrintWriter pw = new PrintWriter(os, "UTF-8");

Is BufferedInputStream and BufferedOutputstream different from InputStream and Outputstream

recently i had troubles working with InputStreams and OutputStreams when i was trying to implement a basic file downloader in my android application.. to elaborate things this is how i did it..
i get an InputStream object using the apache HttpClient classes then tried writing the stream to a file.. but strangely when i buffer the InputStream or the OutputStream i get an unreadable file.... this is the code..
//to make the code concise i removed exceptions and stream closing..
private void download(InputStream in,String fileName){
//if i dont use the buffered thing and read directly from in everything is ok
// same is the buffered out i had to use in/outstream
BufferedInputStream bufferedIn = new BufferedInputStream(in);
FileOutputStream fout = new FileOutputStream(new File(fileName));
BufferedOutputstream bufferedOut = new BufferedOutputstream(fout);
int read = -1;
while((read = bufferedIn.read()) != -1){
bufferedOut.write(read);
}
//close the buffers
}
You have to flush the buffered outputstream when you're done with it.
In any case you probably want to flush() your output (done implicitly by close()), but with BufferedOutputStream this is even more important than with a other OutputStreams. If you have a FileOutputStream, the only buffering performed is that of the OS. If you have a BufferedOutputStream, Java performs its own buffering on top of it.
If you use Java 7 or newer, I'd recommend to write the code like this:
try (BufferedInputStream bIn = new BufferedInputStream(in);
BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(fileName))) {
for (int read; ((read = bIn.read()) != -1; )
bOut.write(read);
}
In your case I suspect you were closing the FileOutputStream but not the BufferedOutputStream. Therefore the file was truncated or even empty because the data buffered in the BufferedOutputStream was not flushed.

Strange behavior of java streaming

I've the necessity to share a streaming of data between two instances as below:
// get EClasses which should be connected
final uk.man.xman.xcore.Parameter source = getParameter(sourceAnchor);
final uk.man.xman.xcore.Parameter target = getParameter(targetAnchor);
// Set data channels
//Output stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream));
source.setOutputStream(dataOutputStream);
//Input stream
DataInputStream inpuDataStream = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(outputStream.toByteArray())));
target.setInputStream(inpuDataStream);
Everything works ok if I write, during those lines of code. Strangely, when I need to use the data channel to write something in another class, like here:
DataOutputStream dataOutputStream = (DataOutputStream) inputParameter.getOutputStream();
System.out.println("WRITE:" + attributes.getValue("value"));
dataOutputStream.writeUTF(attributes.getValue("value"));
dataOutputStream.flush();
I am not able to read, and I really do not know why. Am I missing something?
Thanks for your time
Not sure if that's what you're asking, but you're creating an InputStream that reads from an empty byte array. That doesn't make much sense:
// create an Output stream that will write in memory
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
...
// transform what has been written to the output stream into a byte array.
// Since othing has been written yet, outputStream.toByteArray() returns
// an empty array
DataInputStream inpuDataStream = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(outputStream.toByteArray())));

How to change text file coding charset using java

As in subject. How to rewrite the file with different charset?
Where are can find available encodings - final static ints?
FileInputStream fis = new FileInputStream(inputFile);
InputStreamReader isr = new InputStreamReader(fis, inputEncoding);
BufferedReader in = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(outputFile);
OutputStreamWriter osw = new OutputStreamWriter(fos, outputEncoding);
BufferedWriter out = new BufferedWriter(osw);
String line = in.readLine();
out.write(line);
As in subject. How to rewrite the file with different charset?
I'm not sure why you asked this question as your code seems legit, although it copies only 1 line (and swallows newlines). I wouldn't have used readLine(), but just read() in a loop, maybe with a buffer. This way you copy everything without modifying/swallowing newlines.
Where are can find available encodings - final static ints?
By Charset#availableCharsets().
SortedMap<String, Charset> availableCharsets = Charset.availableCharsets();
// ...
The supported encoding formats are specified in the JDK Documentation.
As per the conversion, you can use
Supported Encodings
Read Encoded Data
Write Encoded Data
Converting between String of different character sets
List all available character set converters

Reading data in Java

What's the difference between using a BufferedReader and a BufferedInputStream?
A BufferedReader is used for reading character data. A BufferedOutputStream is used for writing binary data.
Any classes inheriting from Reader or Writer deal with 16-bit unicode character data, whereas classes inherting from InputStream or OutputStream are concerned with processing binary data. The classes InputStreamReader and OutputStreamWriter can be used to bridge between the two classes of data.
Bufferedreader reads data from a file as a string. BufferedOutputStream writes to a file in bytes. BufferedInputStream reads data in bytes
Sample to Bufferedreader:
try {
BufferedReader br = new BufferedReader(new FileReader(new File(your_file));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
}
Sample to BufferedOutputStream:
//Construct the BufferedOutputStream object
bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));
//Start writing to the output stream
bufferedOutput.write("Line 1".getBytes());
bufferedOutput.write("\r\n".getBytes());
bufferedOutput.write("Line 2".getBytes());
bufferedOutput.write("\r\n".getBytes());
Bufferedinputstream reads in byte:
Sample
:
//Construct the BufferedInputStream object
bufferedInput = new BufferedInputStream(new FileInputStream(filename));
int bytesRead = 0;
while ((bytesRead = bufferedInput.read(buffer)) != -1) {
String chunk = new String(buffer, 0, bytesRead);
System.out.print(chunk);
}
As the names imply, one is for reading data, and the other is for outputting data.

Categories