Hassaan Rabbani
Hassaan Rabbani

Reputation: 2465

Handling a very Large String Java

I am getting a very large STRING for server.

Background: Actually I am converting an image into Base69 string and storing it on my server, than I am calling a service to get back the String. And I am trying to store the String into a String variable like this

String pic="";
if (payload.substring(i, i+10).equals("<picture >")) {
  for (int j=i+10;j<payload.length();j++) {
    if (payload.substring(j, j+5).equals("</pic")) {
      user.setCountry(country);
      user.setDOB(dob);
      user.setUsername(uname);
      user.setPic(pic);
      users.add(user);
      country="";
      uname="";
      pic="";
      dob="";
      i=j+5;
      break;
    } else {
      pic = pic + payload.substring(j, j+1);
    }

But the issue is that after sometime my program crashes and I did not get complete String into the variable pic

Is there a way to handle very long strings coming from the server? I mean to say how can I get the same Base64 String in my variable pic completely so that I decode it back to the picture.

Upvotes: 0

Views: 5096

Answers (2)

Ebbe M. Pedersen
Ebbe M. Pedersen

Reputation: 7488

Find the end of what you want with something like:

int endPos = payload.indexOf("</pic>", currentPos);

and then do one substring that take the full picture data:

String pic = payload.substring(currentPos, endPos);

Upvotes: 1

Ordous
Ordous

Reputation: 3884

Apart from the fact that the code in the if statement seems unrelated to the string at hand, you have String concatenation in a loop in your else statement, which kills performance.

Another point of concern is your abuse of substring(), see Time complexity of Java's substring() (Maybe consider converting the string to an Array or stream?)

Upvotes: 0

Related Questions