2011-11-10 25 views

Respuesta

8

Vea si puede obtener el StringBuffer en un byte[] y luego utilice un ByteArrayInputStream.

+0

+1 Es la respuesta correcta más antigua. –

18

Ver la clase ByteArrayInputStream. Por ejemplo:

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

Tenga en cuenta que es posible que desee utilizar una codificación de caracteres explícita sobre el método getBytes(), por ejemplo:

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

(Gracias @ g33kz0r)

+0

'return new ByteArrayInputStream (sb.toString(). GetBytes (StandardCharsets.UTF_8));' – g33kz0r

2

Ésta es la mejor respuesta que encontrado en Internet. 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"); 
     } 
} 
Cuestiones relacionadas