3

这可能很容易解决,但我现在坚持了一段时间。我有一个用于写入数据的 while 循环。我想将 while 循环中的数据写入字符串。

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);
}

解决了:

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);
}

谢谢你的帮助。

4

6 回答 6

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();
于 2012-09-17T11:20:03.047 回答
5

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

于 2012-09-17T11:19:21.720 回答
2

而不是 System.out 调用只是在循环之前初始化一个 StringBuffer 并附加到它:

StringBuffer s = new StringBuffer();
while ((c = is.read()) != -1) {
  s.append((char) c);
}
于 2012-09-17T11:18:39.387 回答
1

最好使用 StringBuilder 对象而不是 StringBuffer (StringBuilder 和 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);
}
于 2012-09-17T11:20:55.983 回答
1

一种可能性是:

        int c;
    System.out.println("Message: ");
    StringWriter sw = new StringWriter();
    while ((c = is.read()) != -1) {
        sw.write(c);
    }
    System.out.println(sw.toString());
于 2012-09-17T11:24:57.923 回答
1

另一种方法:

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();
于 2012-09-17T11:28:52.443 回答