2011-11-10 41 views

回答

8

查看是否可以将StringBuffer设置为byte[],然后使用ByteArrayInputStream

+0

+1这是最老的正确答案。 –

18

请参阅类ByteArrayInputStream。例如:

public static InputStream fromStringBuffer(StringBuffer buf) { 
    return new ByteArrayInputStream(buf.toString().getBytes()); 
} 

请注意,你可能想在getBytes()方法使用一个明确的字符编码,如:

return new ByteArrayInputStream(buf.toString().getBytes(StandardCharsets.UTF_8)); 

(感谢@ g33kz0r)

+0

'返回新的ByteArrayInputStream(sb.toString()。getBytes(StandardCharsets.UTF_8));' – g33kz0r

2

这是最好的答案我在互联网上找到。 Click Here

import java.io.ByteArrayInputStream; 
import java.io.InputStream; 
public class StringBufferToInputStreamExample { 
     public static void main(String args[]){ 
       //create StringBuffer object 
       StringBuffer sbf = new StringBuffer("StringBuffer to InputStream Example"); 
       /* 
       * To convert StringBuffer to InputStream in Java, first get bytes 
       * from StringBuffer after converting it into String object. 
       */ 
       byte[] bytes = sbf.toString().getBytes(); 
       /* 
       * Get ByteArrayInputStream from byte array. 
       */ 
       InputStream inputStream = new ByteArrayInputStream(bytes); 
       System.out.println("StringBuffer converted to InputStream"); 
     } 
} 
相关问题