3

This is probably very easy to solve, but I am stuck on this for a while now. I got a while loop which I use to write data. I want to write the data from the while loop to a String.

public void dumpPart(Part p) throws Exception {
    InputStream is = p.getInputStream();
    if (!(is instanceof BufferedInputStream)) {
        is = new BufferedInputStream(is);
    }
    int c;
    System.out.println("Message: ");
    while ((c = is.read()) != -1) {
        System.out.write(c);  //I want to write this data to a String.

    }
    sendmail.VerstuurEmail(mpMessage, kenmerk);
}

Solved:

public void dumpPart(Part p) throws Exception {
    InputStream is = p.getInputStream();
    if (!(is instanceof BufferedInputStream)) {
        is = new BufferedInputStream(is);
    }
    int c;
     final StringWriter sw = new StringWriter();
    System.out.println("Message: ");
    while ((c = is.read()) != -1) {
        sw.write(c);
    }
    mpMessage = sw.toString();;
    sendmail.VerstuurEmail(mpMessage, kenmerk);
}

Thanks for your help.

Jef
  • 791
  • 1
  • 18
  • 36

6 Answers6

6

You can consider a java.io.StringWriter (as of JDK 1.4+) :

 System.out.println("Message: ");

 final StringWriter sw = new StringWriter();

 int c;
 while ((c = is.read()) != -1) {
    sw.write(c);
 }

 String data = sw.toString();
Alexandre Dupriez
  • 3,026
  • 20
  • 25
5

I would use IOUtils.toString(inputStream) or something like it.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • this is what I'd prefer if you don't need the while-loop for other reasons. Just convert it with: `String sPart = IOUtils.toString(is);` – Herm Sep 17 '12 at 11:28
2

Instead of the System.out call just initialize a StringBuffer before the loop and append to it:

StringBuffer s = new StringBuffer();
while ((c = is.read()) != -1) {
  s.append((char) c);
}
Dan D.
  • 32,246
  • 5
  • 63
  • 79
1

Its best to do it using the StringBuilder Object rather than StringBuffer ( Difference between StringBuilder and StringBuffer )

public void dumpPart(Part p) throws Exception {
    InputStream is = p.getInputStream();
    if (!(is instanceof BufferedInputStream)) {
        is = new BufferedInputStream(is);
    }
    int c;
    StringBuilder sb = new StringBuilder();
    System.out.println("Message: ");
    while ((c = is.read()) != -1) {
        sb.append(c);

    }
    String result= sb.toString();
    sendmail.VerstuurEmail(mpMessage, kenmerk);
}
Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
1

One possibility is:

        int c;
    System.out.println("Message: ");
    StringWriter sw = new StringWriter();
    while ((c = is.read()) != -1) {
        sw.write(c);
    }
    System.out.println(sw.toString());
Henrique
  • 61
  • 1
  • 1
1

One more way :

StringBuffer buffer = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = is.read(b)) != -1;) {
  buffer.append(new String(b, 0, n));
}
String str = buffer.toString();
Santosh
  • 17,667
  • 4
  • 54
  • 79