将数据写入String

Jef*_*Jef 3 java string object

这可能很容易解决,但我现在坚持了一段时间.我有一个while循环,我用来写数据.我想将while循环中的数据写入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);
}
Run Code Online (Sandbox Code Playgroud)

解决了:

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);
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

Ale*_*iez 6

你可以考虑一个java.io.StringWriter(从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();
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 5

我会使用IOUtils.toString(inputStream)或类似的东西.