string to stream in java without bytearrayinputstream - java

How to convert string to stream in java without using bytearrayinputstream and example?

You could extend the InputStream class and implement the read() method such that it returns data from a String.
But it would be really useless to do that when using a ByteArrayInputStream is so much simpler and easier.

InputStream is = new StringInputStream(string);

Related

Convert OutputStream to ByteArrayOutputStream

I am trying to convert an OutputStream to a ByteArrayOutput Stream. I was unable to find any clear simple answers on how to do this. This question was asked in the title of the question on StackOverflow, but the body of the question aske how to change a ByteArrayStream to OuputStream. I have an OutputStream that is already created and this example given in the answer will not compile!
That Question is Here
I have an OutputStream that is already constructed and has a length of 44 bytes called waveHeader. I want to convert that to a ByteArrayOutputStream because I want to be able to change that into a byte[] with waveHeader.ToByteArray() for simplicity in later processes;
Is there a simple type of casting or something that will allow this?
If not then:
Is there a way to construct a pointer to the data in the original OutputStream if it is not possible to convert it?
How would someone go about accessing the data that is contained in the OutputStream?
I am new to JAVA. This is just a hobby for me. Streams In VisualBasic .net where much easier!
There are multiple possible scenarios:
a) You have a ByteArrayOutputStream, but it was declared as OutputStream. Then you can do a cast like this:
void doSomething(OutputStream os)
{
// fails with ClassCastException if it is not a BOS
ByteArrayOutputStream bos = (ByteArrayOutputStream)os;
...
b) if you have any other type of output stream, it does not really make sense to convert it to a BOS. (You typically want to cast it, because you want to access the result array). So in this case you simple set up a new stream and use it.
void doSomething(OutputStream os)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(something);
bos.close();
byte[] arr = bos.toByteArray();
// what do you want to do?
os.write(arr); // or: bos.writeTo(os);
...
c) If you have written something to any kind of OutputStream (which you do not know what it is, for example because you get it from a servlet), there is no way to get that information back. You must not write something you need later. A solution is the answer b) where you write it in your own stream, and then you can use the array for your own purpose as well as writing it to the actual output stream.
Keep in mind ByteArrayOutputStreams keep all Data in Memory.
You could use the writeTo method of ByteArrayOutputStream.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[8];
bos.write(bytes);
bos.writeTo(oos);
You can create an instance of ByteArrayOutputStream. You then need to write the data to this ByteOutputStream instance and then using the writeTo method, which accepts an OutputStream, you can enable the ByteArrayOutputStream to write the output, to the instance of OutputStream which you passed as the argument.
Hope it works!
You can use toByteArray function on the output stream you have.That's is let say you have outputStream buffer So you can do buffer.toByteArray .
For more you can look at the answer of Convert InputStream to byte array in Java .

what is the difference between these two ways of writing to a file in java?

I have two implementations below, where the PrintStream object wraps either FileOutputStream object or File object. I get the same thing done with both. Are there any difference between them where one method will not be applicable to write.
public class Varags {
public static void main(String[] args) throws FileNotFoundException{
OutputStream output = new FileOutputStream("Test.txt");
PrintStream p1=new PrintStream( output);
p1.println("trying");
PrintStream p=new PrintStream( new File("test2.txt"));
p.println("trying");
}
}
Are there other way of writing to file that is better than these?
Thanks
As far as I know there is no difference. According to the Javadocs the File version creates an OutputStreamWriter anyways, and is only included for convenience.
In many cases, using a Writer is better for plain text input. If you're working with raw byte data then streams such as FileInputStream, FileOutputStream, etc. will be necessary.
PrintStream provides some convenience methods for writing text to a file. To get more control about writing characters to a file, use PrintWriter.
OutputStream is used to write bytes (pure data, not just text) to a file.

Serialisation without use ObjectOutputStream

It can possible to serialise an object without used ObjectOutputStream ?
Until now i find just this two solution to serialize and object :
FileOutputStream fichier = new FileOutputStream("File.ser");
ObjectOutputStream oos = new ObjectOutputStream(fichier);
stream.writeObject(m);
Or
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteOutput);
stream.writeObject(m);
To serialize just means to produce a stream of data from an object which, at some later time, can be used to reproduce the same object. Therefore, by definition, yes. You can write any number of alternative serialization mechanisms.
Now, would you want to do this? No, probably not. If you don't like Java's default serialization format, the externalization mechanism gives you the hooks to change it however you'd like.

Reading Objects from Random Access File

I wrote a file using Java's FileChannel class that uses RandomAccessFiles. I wrote objects at various locations in the file. The objects were of variable sizes but all of the same class. I wrote the objects using the following idea :
ByteArrayOutputStream bos= new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(r);
byte[] recordBytes= bos.toByteArray();
ByteBuffer rbb= ByteBuffer.wrap(recordBytes);
while(rbb.hasRemaining()) {
fileChannel.write(rbb);
}
Now I want to read from such a file. I dont want to have to specify the number of bytes to read. I want to be able to read the object directly using Object Input Stream. How to achieve this ?
I have to use Random Access Files because I need to write to different positions in file. I am also recording in a separate data structure, the locations where objects have been written.
I have to use Random Access Files because I need to write to different
positions in file.
No, you don't. You can reposition a FileOutputStream or FileInputStream via its channel.
That would significantly simplify your writing code as well: you wouldn't need to use the buffer or channel, and depending on your needs you could omit the ByteArrayOutputStream as well. However, as you note in a comment, you won't know the size of the object in advance, and the ByteArrayOutputStream is a useful way to verify that you don't overrun your allotted space.
Object obj = // something
FileOutputStream fos = // an initialized stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
if (bos.size() > MAX_ALLOWED_SIZE)
throw // or log, or whatever you want to do
else
{
fos.getChannel().position(writeLocation);
bos.writeTo(fos);
}
To read the objects, do the following:
FileInputStream fis = // an initialized stream
fis.getChannel().position(offsetOfSerializedObject);
ObjectInputStream iis = new ObjectInputStream(new BufferedInputStream(fis));
Object obj = iis.readObject();
One comment here: I wrapped the FileInputStream in a BufferedInputStream. In this specific case, where the file stream is repositioned before each use, that can provide a performance benefit. Be aware, however, that the buffered stream can read more bytes than are needed, and there are some situations using construct-as-needed object streams where it would be a really bad idea.
Why doesn't seek work for you? I believe you need to seek() to correct locations and then just read objects using your object stream. Also, if you store the correct locations of serialized objects, why don't you store their sizes? In this case you may apply ObjectInputStream against bytes you read from file.
The simplest solution that comes to mind is to write out the length of the array before writing out the array itself:
while(rbb.hasRemaining()) {
fileChannel.writeLong(recordBytes.length);
fileChannel.write(rbb);
}
When reading the object, you first read the length. This'll tell you how many further bytes to read to get your object. Similarly to what you are already doing on the writing side, you could read the data into a byte[] and then use ByteArrayInputputStream and ObjectInputStream.
You could use a FileInputStream constructed on the RandomAccesFile's FileDescriptor object, like so:
FileDescriptor f = raf.getFD();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Assuming that the RandomAccessFile is called raf.

Best way to send an ArrayList<String[]> over TCP in Java?

I'm writing a client/server application in Java and I'm using TCP to transfer data which I'm storing in an ArrayList (i.e. An ArrayList of arrays of Strings).
What is the best way to transfer that data from one to the other? Should I make one long string and use a PrintWriter's println() or is there a better way?
Thanks very much!
Assuming both client and server and written in Java, and assuming you're stick with raw sockets, rather than a higher-level remoting framework:
OutputStream socketStream = ...
ObjectOutput objectOutput = new ObjectOutputStream(socketStream);
objectOutput.writeObject(myDataList);
Similarly, use ObjectInputStream at the receiving end.
Should work nicely, as long as everything inside the list implements java.io.Serializable.
To add a bit to skaffman's answer:
OutputStream socketStream = ...
GZIPOutputStream objectOutput = new GZIPOutputStream(new ObjectOutputStream(socketStream));
objectOutput.writeObject(myDataList);
And on the client:
InputStream socketStream = ...
ObjectInputStream objectInput = new ObjectInputStream(new GZIPInputStream(socketStream));
ArrayList<type> a = objectInput.readObject();
You might want to consider the JSON framework. See json.org JSON = Javascript Object Notation. Even though the name suggests the use of Javascript, the json.jar is a good serialization/deserialization tool.
Many people would use a web service framework for this, such as Apache CXF. You could also go one level down to JAXB or XML Beans.
You may want to look into Serialization. You could just make up your own format for such a simple case, though. Personally I favour bencoding. The minimum effort (and least bug-prone) solution here is Serialization, though.

Categories

Resources