java - 将数据写入字符串

标签 java string object

这可能很容易解决,但我现在坚持了一段时间。我有一个 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);
}

感谢您的帮助。

最佳答案

您可以考虑一个 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();

关于java - 将数据写入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458081/

相关文章:

ruby - 为什么这个 "Freeze"不是字符串?

java - Java 中的 "Module"功能?

java - 匹配冒号两边的文本

c - 将字符串分配给C中结构中的元素

javascript - 考虑数字位数的增量字符串 (0, 1, 2, ..., 9, 00, 01)

java - java中删除字符串中的常见字符串字符

java - 需要更好的 Java 应用程序部署策略

java - eclipse RCP : Suppress the context menu of the persective bar

javascript - 将函数分配给对象属性

java - JUnit 4 预期异常类型