[ACCEPTED]-Custom implementation of InputStream-java-io
You only nead to implement the read()
method without parameters. All other methods 4 are implemented as calls to that method. For 3 performance reasons (and even ease of implementation) it 2 might be easier to implement the three-argument read()
method instead and re-implement 1 the no-args read()
method in terms of that method.
Some very important points which I met when 20 implementing my InputStream
.
Override available(). As 19 the Javadoc says:
The available method for 18 class InputStream always returns 0. This 17 method should be overridden by subclasses.
not 16 overriding this method will causes that 15 any tempt to test whether this stream is 14 readable return false. For example, if you feed your 13
inputStream
to ainputStreamReader
, this reader will always return false when you invoke 12reader.ready()
.return -1 in the
read()
. The doc didn't emphasize 11 it:If no byte is available because the end 10 of the stream has been reached, the value 9 -1 is returned. This method blocks until 8 input data is available, the end of the 7 stream is detected, or an exception is thrown.
if 6 you choose to block
read()
when no data is available, you 5 have to remember toreturn -1
at some situations. Not 4 doing this may causes that anotherread(byte b[], int off, int len)
blocks 3 for the following code in the source:for (; i < len ; i++) {// default len is a relative large number (8192 - readPosition) c = read(); if (c == -1) { break; } b[off + i] = (byte)c; }
And 2 this causes some(if not all) high level 1 read block, like a reader's
readLine(), read()
etc.
For possibly large data you can use com.google.common.io.FileBackedOutputStream from 1 guava.
Javadoc: An OutputStream that starts buffering to a byte array, but switches to file buffering once the data reaches a configurable size.
Using out.getSupplier().getInput()
you get your InputStream.
There's absolutely no need to create a custom 7 InputStream
. Use ByteArrayInputStream
, something like this:
public static InputStream createStream(){
final String csv = createCsvFromDataBaseValues();
return new ByteArrayInputStream(csv.getBytes());
}
Especially given 6 this quote:
My idea is to load all the data 5 in the constructor and then override the 4 read method.
If you do it like this, you 3 gain absolutely nothing by implementing 2 a custom InputStream
. It's pretty much equivalent to 1 the approach I outlined above.
Why do you need a custon inputstream? why 3 not just write the csv data as you generate 2 it to the outputstream being written to 1 the ftp server?
If the data is not too large, you could:
- Read it all
- Convert to CSV (text)
- Get the text bytes (via
String.getBytes(encoding)
) - But the byte array in a
ByteArrayInputStream
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.