I am trying to redirect System.out into a String using System.setOut, which takes a PrintStream. Is there any way to convert a StringWriter into a Stream so that I can pass it to setOut?
You can't do that exactly, since StringWriter is a Writer, not a Stream. But you can do this:
// create a ByteArray stream, which will be wrapped by a PrintStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setOut(ps);
// print whatever you got
String result = baos.toString();
Related
I am writing a csv file in a very old java application so i can not use all the new Java 8 streams.
Writer writer = new OutputStreamWriter(new FileOutputStream("file.csv"));
writer.append("data,");
writer.append("data,");
...
Then I need to transform the writer object into a ByteArrayInputStream.
How can i do it ?
Thanks in advance.
Best regards.
This depends on what you are trying to do.
If you are writing a bunch of data to the file and THEN reading the file you will want to use a FileInputStream in place of your ByteArrayInputStream.
If you want to write a bunch of data to a byte array then you should take a look at using a ByteArrayOutputStream. If you then need to read the byte array as a ByteArrayInputStream you can pass the ByteArrayOutputStream into the input stream like what is shown below. Keep in mind this only works for writing and THEN reading. You can not use this like a buffer.
//Create output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Create Writer
Writer writer = new OutputStreamWriter(out);
//Write stuff
...
//Close writer
writer.close();
//Create input stream using the byte array from out as input.
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Short answer: you can't.
A ByteArrayInputStream is just not assignable from a OutputStreamWriter.
Since you're probably after write, you can just read the file back to a byte[] and then construct a ByteArrayInputStream with it:
File file = new File("S:\\Test.java");
FileInputStream fis = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
fis.read(content,0,content.length);
ByteArrayInputStream bais = new ByteArrayInputStream(content);
I'm having this problem when trying to write into a txt file on my server from a Java program. Even though it writes the text, it writes some strange chars in front of it. My code looks like this:
URL urlOutput = new URL("ftp://username:password#ftp.matsworld.io");
URLConnection urlc = urlOutput.openConnection();
OutputStream os = urlc.getOutputStream();
OutputStream buffer = new BufferedOutputStream(os);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject("Hello world!");
output.close();
buffer.close();
os.close();
And this is what appears in the txt file:
¨ŪtKVHello world!
Thanks for help!
ObjectOutputStream is used for object serialization. The part preceding "Hello world!" is the "bookkeeping" information saved by the object output stream for the object input stream to figure out what kind of object is being restored.
Use PrintStream for outputting textual information:
URL urlOutput = new URL("ftp://username:password#ftp.matsworld.io");
URLConnection urlc = urlOutput.openConnection();
OutputStream os = urlc.getOutputStream();
OutputStream buffer = new BufferedOutputStream(os);
PrintStream output = new PrintStream(buffer);
output.writeLine("Hello world!");
output.close();
buffer.close();
os.close();
I would like to persist a sort of object using ObjectOutputStream into stringwriter as a last outoput data. If this was not clear check out this piece of code bellow.
StringWriter sw = new StringWriter();
OutputStream out = null ; which object wrap sw here?
try (ObjectOutputStream obj = new ObjectOutputStream(out)){
} catch (IOException e) {
e.printStackTrace();
}
As you can see which class should I use to wrap an object of Stringwriter.
Here's a working snippet of code:
// Create a base 64 encoded string and print it
byte[] data = {-1,-2,-3,0,1,2,3,};
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream enc = new ObjectOutputStream( bos );
enc.writeObject( data );
enc.close();
String b64 = Base64.getEncoder().encodeToString( bos.toByteArray() );
System.out.println( "data=" + b64 );
Don't use a StringWriter, use a ByteArrayOutputStream. The Writer interface and the OutputStream interface are two different things and you can't mix them up.
How do i convert type
Stream<Object> into an InputStream? Currently, I get the iterator and loop through all of the data converting it to a byteArray and adding it to an inputStream:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
Iterator<MyType> myItr = MyObject.getStream().iterator();
while (myItr.hasNext()) {
oos.writeObject(myItr.next().toString()
.getBytes(StandardCharsets.UTF_8));
}
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(bao.toByteArray());
What is the overhead of doing this though? If my stream contains a terabyte of data, wouldn't I be sucking a terabyte of data into memory? Is there any better way to achieve this?
You should be able to convert the OutputStream into an InputStream using a pipe:
PipedOutputStream pos = new PipedOutputStream();
InputStream is = new PipedInputStream(pos);
new Thread(() -> {
try (ObjectOutputStream oos = new ObjectOutputStream(pos)) {
Iterator<MyType> myItr = MyObject.getStream().iterator();
while (myItr.hasNext()) {
oos.writeObject(myItr.next().toString()
.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
// handle closed pipe etc.
}
}).start();
Inspired by this answer.
Would this work for you?
https://gist.github.com/stephenhand/292cdd8bba7a452d83c51c00d9ef113c
It's an InputStream implementation that takes a Stream<byte[]> as input data. You just need to .map() your abitrary objects to byte arrays however you want each object to be represented as bytes.
It only calls a terminal operation on the Stream when the InputStream is read, pulling objects off the Stream as the consumer reads more of the InputStream so it never loads the whole set into memory
I am about to write junit tests for a XML parsing Java class that outputs directly to an OutputStream. For example xmlWriter.writeString("foo"); would produce something like <aTag>foo</aTag> to be written to the outputstream held inside the XmlWriter instance. The question is how to test this behaviour. One solution would of course be to let the OutputStream be a FileOutputStream and then read the results by opening the written file, but it isn't very elegant.
Use a ByteArrayOutputStream and then get the data out of that using toByteArray(). This won't test how it writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.
If you can pass a Writer to XmlWriter, I would pass it a StringWriter. You can query the StringWriter's contents using toString() on it.
If you have to pass an OutputStream, you can pass a ByteArrayOutputStream and you can also call toString() on it to get its contents as a String.
Then you can code something like:
public void testSomething()
{
Writer sw = new StringWriter();
XmlWriter xw = new XmlWriter(sw);
...
xw.writeString("foo");
...
assertEquals("...<aTag>foo</aTag>...", sw.toString());
}
It's simple. As #JonSkeet said:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// pass the baos to be writed with "value", for this example
byte[] byteArray = baos.toByteArray();
Assert.assertEquals("value", new String(byteArray));