Reading an Inputstream into a Data Object

Reading an InputStream into a Data object

I could not find a nice way. We can create a nice-ish wrapper around the unsafe stuff:

extension Data {
init(reading input: InputStream) throws {
self.init()
input.open()
defer {
input.close()
}

let bufferSize = 1024
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer {
buffer.deallocate()
}
while input.hasBytesAvailable {
let read = input.read(buffer, maxLength: bufferSize)
if read < 0 {
//Stream error occured
throw input.streamError!
} else if read == 0 {
//EOF
break
}
self.append(buffer, count: read)
}
}
}

This is for Swift 5. Find full code with test (and a variant that reads only some of the stream) here.

How do I read / convert an InputStream into a String in Java?

A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or even

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);

Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers

How to Read Specific data from to InputStream object?

Try this I was getting JSONObject in my case :

static InputStream is = null;


try {

BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);

StringBuilder sb = new StringBuilder();

String line = null;

while ((line = reader.readLine()) != null) {

sb.append(line + "\n");

}

is.close();

json = sb.toString();

} catch (Exception e) {

e.printStackTrace();
}

How much data does inputstream.read reads in java

The whole point of this interface (or to be precise: abstract class): you can absolutely not rely on assuming how many bytes were read. You always always always have to check the return value of that method to know.

Background: there are many different implementations for this interface. Some my buffer, some may not. Some read "fixed" input (maybe from existing data in memory). Somebody might decide to give you a stream that turns to the internet, download a 10 GB file and then start sending you one byte after the other.

The only thing you know is: the method returns

the total number of bytes read into the buffer

End of story.

How do I read / convert an InputStream into a String in Java?

A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or even

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);

Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers

Reading Objects From A File to An Input Stream

It sounds like you originally just wrote the Product objects to an ObjectOutputStream, rather than a Map<Integer, Product>. If that's the case, you need something like:

Map<Integer, Product> products = new TreeMap<>();
try (ObjectInputStream input = new ObjectInputStream(new FileInputStream(file))) {
while (true) {
Product product = (Product) input.readObject();
products.put(product.getCode(), product); // Or whatever
}
} catch (EOFException e) {
// Just finish? Kinda nasty...
}

Of course, that will throw an exception when it reaches the end of the stream - you might want to think about how you're going to detect that cleanly rather than just handling the exception.

Append InputStream object to String object

The usual way to read character data from an InputStream is to wrap it in a Reader. InputStreams are for binary data, Readers are for character data. The appropriate Reader to read from an InputStream is the aptly named InputStreamReader:

Reader r = new InputStreamReader(stdout, "ASCII");
char buf = new char[4096];
int length;
StringBuilder s = new StringBuilder();
while ((length = r.read(buf)) != -1) {
s.append(buf, 0, length);
}
String str = s.toString();

Note that appending to a String repeatedly inside a loop is usually a bad idea (because each time you'll need to copy the whole string), so I'm using a StringBuilder here instead.



Related Topics



Leave a reply



Submit