This question already has answers here:
Get an OutputStream into a String
(6 answers)
Closed 9 years ago.
I think this has been answered but I can't seem to find it.
I have an instance method which writes some contents to an output stream
writeTo(OutputStream){
//class specific logic
}
I want it to get these contents into a StringBuilder. I can do this via a temporary file but that does not seem right. I want to do something like:
Stringbuilder sb = /* */;
OutputStream os = outForStringBuilder(sb);//not sure how to do this
instance.writeTo(os); //This should write the contents to Stringbuilder
Use a ByteArrayOutputStream and then call toString(charSet) - no need for a StringBuilder.
So you are wanting output written to the stream to go to a StringBuffer instead. I am assuming you are doing this because an OutputStream is required somewhere else. You could use ByteArrayOutputStream, but if you want to preserve the StringBuffer behavior, you might simply wrap a StringBuffer in a subclass of OutputStream like the code here:
http://geronimo.apache.org/maven/specs/geronimo-javamail_1.4_spec/1.6/apidocs/src-html/org/apache/geronimo/mail/util/StringBufferOutputStream.html#line.31
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I'm using a specific library (unfortunately can't be avoided) that writes some information from a class to a file using a utility function that receives a DataOutputStream as the input.
I would like to get the resulting file's content as a String without actually creating a file and writing into it as the writing can be pretty "taxing" (1000+ lines).
Is this possible to do by using a dummy DataOutputStream or some other method and without resorting to creating a temporary file and reading the result from there?
P.S: the final method that actually writes to the DataOutputStream changes from time to time so I would prefer not actually copy-paste it and redo it every time.
As java.io.DataOutputStream wraps around just any other java.io.OutputStream (you have to specify an instance in the constructor) I would recommend that you use a java.io.ByteArrayOutputStream to collect the data in-memory and get the String of that later with the .toString() method.
Example:
ByteArrayOutputStream inMemoryOutput = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(inMemoryOutput);
// use dataOutputStream here as intended
// and then get the String data
System.out.println(inMemoryOutput.toString());
If the encoding of the collected bytes does not match the system default encoding, you might have to specify a Charset as parameter of the toString.
This question already has an answer here:
Modify file using Files.lines
(1 answer)
Closed 7 years ago.
Suppose I have a java.util.stream.Stream of objects with some nice toString method:
What's the shortest/most elegant solution to write this stream to a file, one line per stream element?
For reading, there is the nice Files.lines method, so I thought there must be a symmetric method for writing to file, but could not find one.
Files.write only takes an iterable.
Probably the shortest way is to use Files.write along with the trick which converts the Stream to the Iterable:
Files.write(Paths.get(filePath), (Iterable<String>)stream::iterator);
For example:
Files.write(Paths.get("/tmp/numbers.txt"),
(Iterable<String>)IntStream.range(0, 5000).mapToObj(String::valueOf)::iterator);
If it looks too hackish, use more explicit approach:
try(PrintWriter pw = new PrintWriter(Files.newBufferedWriter(
Paths.get("/tmp/numbers.txt")))) {
IntStream.range(0, 5000).mapToObj(String::valueOf).forEach(pw::println);
}
If you have stream of some custom objects, you can always add the .map(Object::toString) step to apply the toString() method.
This question already has answers here:
How to write data to two java.io.OutputStream objects at once?
(5 answers)
Closed 8 years ago.
I have an OutputStream, and I'd like to (on a conceptual level) broadcast it to multiple files. So for instance, if a byte shows up in the stream, I want that to get written to files A, B, and C.
How can I accomplish this using only one stream? Preferably with a pure Java solution.
You can use Apache Commons IO TeeOutputStream for this purpose.
This OutputStream proxies all bytes written to it to two underlying OutputStreams.
You can use multiple TeeOutputStreams in a chain when you want to write to more than two OutputStreams at once.
OutputStream out = new TeeOutputStream(new FileOutputStream(new File("A")), new TeeOutputStream(new FileOutputStream(new File("B")), new FileOutputStream(new File("C")))))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I am having problems reading from a serialized file.
More specifically, I have serialized an object to a file written in a hexadecimal format. The problem occurs when I want to read one line at a time from this file. For example, the file can look like this:
aced 0005 7372 0005 5465 7374 41f2 13c1
215c 9734 6b02 0000 7870
However, the code underneath reads the whole file (instead of just the first line). Also, it automatically converts the hexadecimal data into something more readable: ¬ísrTestAòÁ
....
try (BufferedReader file = new BufferedReader(new FileReader(fileName))) {
read(file);
} catch ...
....
public static void read(BufferedReader in) throws IOException{
String line = in.readLine();
System.out.println(line); // PROBLEM: This prints every line
}
}
This code works perfectly fine if I have a normal text file with some random words, it only prints the first line. My guess is the problems lies in the serialization format. I read somewhere (probably the API) that the file is supposed to be in binary (even though my file is in hexadecimal??).
What should I do to be able to read one line at a time from this file?
EDIT: I have gotten quite a few of answers, which I am thankful for. I never wanted to deserialize the object - only be able to read every hexadecimal line (one at a time) so I could analyze the serialized object. I am sorry if the question was unclear.
Now I have realized that the file is actually not written in hexadecimal but in binary. Further, it is not even devided into lines. The problem I am facing now is to read every byte and convert it into hexadecimal. Basically, I want the data to look like the hexadecimal data above.
UPDATE:
immibis comments helped me solve this.
"Use FileInputStream (or a BufferedInputStream wrapping one) and call read() repeatedly - each call returns one byte (from 0 to 255) or -1 if there are no more bytes in the file. This is the simplest, but not the most efficient, way (reading an array is usually faster)"
The file does not contain hexadecimal text and is not separated into lines.
Whatever program you are using to edit the file is "helpfully" converting it into hexadecimal for you, since it would be gibberish if displayed directly.
If you are writing the file using ObjectOutputStream and FileOutputStream, then you need to read it using ObjectInputStream and FileInputStream.
Your question doesn't make any sense. Serialized data is binary. It doesn't contain lines. You can't read lines from it. You should either read bytes, with an InputStream, or objects, with an ObjectInputStream.
This question already has answers here:
I want to print any text without using Print function in java?
(5 answers)
Closed 8 years ago.
I have no idea how to start writing a java code to print
a string without using any inbuilt function like println etc.
Does anyone know how to write it?
I will not paste you all the article you can read here: http://luckytoilet.wordpress.com/2010/05/21/how-system-out-println-really-works/
But read it and look the repetition of "native" word.
Then you can jump to this other post : What is a native implementation in Java?
Then, you will have the presumption that you cannot write to process standard stream (or error) without using any native function, because you need something runnable on different OS... and that's the goal of the JVM.
You can write it using PrintWriter class
PrintWriter printWriter = new PrintWriter(System.out);
printWriter.write("Hello");
printWriter.flush();
printWriter.close();