This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

Talk about the current requirements scenario

Recently, a company wanted to access a third-party service in a project, where it downloaded a report file and fed it back through an interface.

The download interface returns a string of bytes, such as [1,2,3,4,5,6,7], but of course the real data does not look like this.

But how do we turn this byte string into a file stream?

Let’s take a look and share my thoughts on how to deal with it.

Try going straight to a string followed by a byte array

I got the string first, but there is no way to convert it directly to the byte array byte[].

This is where I came up with a solution, which is to directly convert this byte string into a string, which is the following code:

Object obj = ",2,3,4,5,6,7 [1]";

String string = (String) obj;

byte[] bytes = string.getBytes();

InputStream inputStream = new ByteArrayInputStream(target);
Copy the code

Unfortunately, this is wrong and unclear.

There is no way, but to find another way.

Try again for special compliance with [] and comma failure.

So I tried it again, and here’s the code:

Object obj = ",2,3,4,5,6,7 [1]";

String string = (String) obj;

string = string.replace("["."").replace("]"."").replace(","."");

byte[] bytes = string.getBytes();

InputStream inputStream = new ByteArrayInputStream(target);
Copy the code

In the code above, we replace the commas and brackets in the string before converting it to a byte array.

Unfortunately, also failed, there is no way to find another way.

Finally, not wanting to waste too much time, I checked to see if any third-party services provided code samples

Wow, that’s true, so I gave you a code example that’s a little sloppy, but crucial.

I put the code example how to convert the byte array method posted for you to learn.

Object obj = ",2,3,4,5,6,7 [1]";
String string = (String) obj;
ObjectMapper mapper = new ObjectMapper();
byte[] target = mapper.readValue(string , new TypeReference<byte[] > () {});Copy the code

The best solution is this, unavoidable sigh, we still want to use more resources can be used, some cases may be very simple to solve, there is no need to go too deep, I hope we can learn from it.