OutputStream to String/StringBuffer?

How can I convert a OutputStream into a String or StringBuffer?

<OutputStream>.toString();In what context do you use this?It is inherited from Object.
This will give you a "string representation" of the stream object. Normally, this will just return an object identifier. I use this when I'm debugging or printing low level logging messages to help determine exactly which object I'm dealing with.
- K
PS - If you want to convert a stream to a String, you probably want to be using a Writer instead of a stream. Writers are character set encoding aware...

Similar Messages

  • Converting OutputStream to String

    This is a stupid question, but...How do you convert OutputStream to a String. For example i get output stream by:
    OuputStream os = process.getOutputStream();
    Now I want to convert that stream into a string. How would I do that? How do I use the write() method? I don't have to write the stream anywhere, I just need it in the form of a string. When i simply use os.toString(), it converts the stream to some encrypted code. I need to convert it so the stream is readable.
    Thanks.

    import java.io.*;
    class PipingDemo {
        public static void main(String[] args) throws Exception {
            final PipedInputStream inPipe = new PipedInputStream();
            PipedOutputStream outPipe = new PipedOutputStream(inPipe);
            OutputStreamWriter osWriter = new OutputStreamWriter(outPipe);
            PrintWriter out = new PrintWriter(osWriter);
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(inPipe));
                        String line;
                        StringBuffer output = new StringBuffer();
                        while((line = in.readLine()) != null) {
                            output.append(line);
                            output.append(System.getProperty("line.separator"));
                        in.close();
                        System.out.println(output.toString());
                    } catch (IOException e) {
                        e.printStackTrace();
            thread.start();
            out.write("Shama Lama rama rama rama ding dong");
            out.write("\nYou put the ooh mau mau oh oh oh oh");
            out.write("\nBack into my smile, child");
            out.write("\nThat is why (That is why)");
            out.write("\nYou are my sugar dee dee doo");
            out.close();
    }

  • How to convert OutputStream to String?

    I'm trying to convert an outputstream to a String, but I'm not succeeding. Anyone any clues? Thx

    they Were right.
    But outpoutstream and inputstream just a "data"
    if you want to see it, this may Help.
    i try see from another java forum.
    /* author : "Joe" <[email protected]> */
    import java.io.*;
    public class IOString {
    private StringBuffer buf;
    /** Creates a new instance of IOString */
    public IOString() {
    buf = new StringBuffer();
    public IOString(String text) {
    buf = new StringBuffer(text);
    public InputStream getInputStream() {
    return new IOString.IOStringInputStream();
    public OutputStream getOutputStream() {
    return new IOString.IOStringOutputStream();
    public String getString() {
    return buf.toString();
    class IOStringInputStream
    extends java.io.InputStream {
    private int position = 0;
    public int read() throws java.io.IOException {
    if (position < buf.length()) {
    return buf.charAt(position++);
    else {
    return -1;
    class IOStringOutputStream
    extends java.io.OutputStream {
    public void write(int character) throws java.io.IOException {
    buf.append( (char) character);
    public static void main(String[] args) {
    IOString target = new IOString();
    IOString source = new IOString("Hello World.");
    convert(target.getOutputStream(), source.getInputStream());
    System.out.println(target.getString());
    /** <CODE>convert</CODE> doesn't actual convert anything but copies byte
    for byte
    public static boolean convert(java.io.OutputStream out,
    java.io.InputStream in) {
    try {
    int r;
    while ( (r = in.read()) != -1) {
    out.write(r);
    return true;
    catch (java.io.IOException ioe) {
    return false;
    Regs,
    dedi mulyana

  • How to display the multiple lines text in a single - String, StringBuffer

    Hi,
    I have a textarea field named Decription which contains more than one line seperated by new line.I need to display those five lines in a single text without breaking. Is it possible? I am getting ArrayIndexOutOfBoundsException while i reached to the end of the line. Plz help me how to align the below code so that i can display the lines as a single line in my excel sheet.
                        if(op.getDescription()!=null)
                            String[] oppDescs = op.getDescription().split("\n");
                            StringBuffer sb = new StringBuffer();
                            for(int i1=0; i<=oppDescs.length-1;++i1)
                                *writeFile(sb.append(oppDescs[i1]), valueWriter);*
                         } else {
                            writeFile(op.getDescription(), valueWriter);
    private void writeFile(java.lang.Object value,PrintWriter valueWriter)
            if(value!=null)
                valueWriter.print(value);   
        }Thanks and Regards

    previous was java1.5
    heres a 1.1 - 1.4 version
    String[] oppDescs = op.getDescription().split("\n");
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < oppDescs.length : i++){
      sb.append(oppDescs);
    sb.append( '\t' );
    writeFile(sb.toString(), valueWriter );Edited by: simon_orange on 31-Oct-2008 13:02                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Truncating Strings(stringbuffer)

    Hello again
    im trying to delete portions of a string that are over a certain length, i know i need to use StringBuffer and public delete(int start, int end) command, but i am having trouble working it in, how do i initialize a Stringbuffer?
    Stringbuffer serverNameBuff=new StringBuffer(serverName); is meant to create a StringBuffercopy of the string serverName, what am i doing wrong?
    THankyou
    dom

    lol damn, sorry, i see now...lowercase b...nevermind, but thanks anyway

  • String & StringBuffer again......

    hi all,
    after coding for 1 year with java (before c++ for years) i used the stringbuffer class for the first time a few days ago.
    i implemented a search which has to do lot's (!) of string operations.
    the search was very slow, so i tried stringbuffer.
    i replaced and changed all the string stuff into stringbuffer stuff - but the performance was still bad...
    so could the following be the problem:
    stringbuffer don't know important functions like 'indexof(String)'.
    so everytime i need indexof (for example), i do the toString() function...
    now my first question:
    is all the stringbuffer advantage gone if i use toString() at one or to places ==> how much performance will this cost (in a loop...)?
    my second question:
    what's faster, deleting the content of an used stringbuffer with delete(int,int) or just creating a new with new stringbuffer(String) ?
    thanx a lot,
    andi

    What you should probably do is use "javap -c" to look at the bytecode produced in your class. Then you can see exactly how many objects are being created for each way of coding the String and StringBuffer operations.
    To answer your question about toString(), it creates an extra String object when called, but does not copy the characters. However, if you subsequently change the original StringBuffer, the characters in it will need to be copied. Therefore, calling toString() and then changing the StringBuffer further can have a serious impact on performance.

  • OutputStream to String

    Please Help... How do you convert OutputStream to a String?
    I have tried in the forum.. but I have found nothing.
    Thanks!

    I'm developing an XML application with JOX (http://sourceforge.net/projects/jox )
    I have to read an XML file.. work on it and send it as String to an XML Processor (Server).
    The folliwing line create a JOXBeanOutputStream :
    FileOutputStream fileOut = new FileOutputStream("C:/jakarta-tomcat-5.0.27/webapps/xerces/jox/airaalairprvdpREQUESTDTD.xml");
    JOXBeanOutputStream joxOut = new JOXBeanOutputStream(fileOut, "UTF-8");
    where :
    java.lang.Object
    |
    --java.io.OutputStream
    |
    --java.io.FilterOutputStream
    |
    --com.wutka.jox.JOXBeanOutputStream
    and the line :
    joxOut.writeObject(...);
    write this OutputStream to a file (airaalairprvdpREQUESTDTD.xml)... but i need a String not another XML file!
    This is my problem...

  • JNI: Getting String | StringBuffer  to Java from C using input argument

    I've written a native method in C which takes command String from Java, executes the command, and obtains both an integer return_code and a C-string result_string as an output. The return_code goes back to Java from the return statement at the end of the native method...my problem is, that I would like to pass into the native method either a String or StringBuffer, and use that to relay the result_string back to the Java code, as well. Eg., loosely, if I have a
    JNIEXPORT jint JNICALL ExecuteCmd
    (JNIEnv *env, jclass jcls, jstring cmdString, jobject returnBuffer)
    where jobject returnBuffer is a StringBuffer created as StringBuffer(2048), I'd like to take return_string once I have it and do something like
    returnBuffer = env->NewStringUTF(result_string);
    (I know the syntax env->NewStringUTF is a bit different to what's in the JNI book, but it's what works on the HP-UX system I'm using.)
    I know already that this particular bit of code doesn't work. My question is, does the general idea have any potential to work, or am I trying to do something that's impossible?

    Your general approach works just fine. What you have to do is use JNI to find the appropriate method for the StringBuffer class, and invoke it.

  • String & StringBuffer

    Hi,
    Why String objects are Immutable?
    and StringBuffer objects are mutable.
    what is the logic behind this design.
    thanks in advance.

    My theory on this is that Strings occupy fixed contiguous areas of memory. To alter them may corrupt the area of memory that comes immeadiately after a particular String. Therefore it is safe to not let programmers to alter them. A StringBuffer on the other hand overcomes this restriction and will allow expansion of itself by the programmer to other areas of memory, under control of the compiler, when required.

  • String , StringBuffer Performace

    I am trying to concatenate strings. In the following program, f2 and f3 take less than a second while f1 takes about 17 seconds on my P4 1.3 Ghz pc. Any ideas why += operation takes more time.
    public class StringTest
    public static void main(String s[])
    long start_time = System.currentTimeMillis() ;
    if (s[0].equals("1")) f1();
    if (s[0].equals("2")) f2();
    if (s[0].equals("3")) f3();
    long end_time = System.currentTimeMillis() ;
    System.out.println("Time in sec: " + (end_time-start_time)/1000);
    public static String f1()
    String s = "";
    for (int i=0;i<10000;i++)
    s += new String("Helloworld");
    return s;
    public static String f2()
    StringBuffer s = new StringBuffer();
    for (int i=0;i<10000;i++)
    s.append("HelloWorld");
    return s.toString();
    public static String f3()
    String s = "";
    for (int i=0;i<10000;i++)
    s = new String("Helloworld");
    return s;
    }

    It's terrifying indeed...
    Here are my results on a IBM ThinkPad PM 1.7 GHz 512 Mb with Windows XP Pro SP2
    For JVMs from 1.4 to 1.6.
    (I modified the println line to get double result)
    java -version
    java version "1.4.2"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2)
    Classic VM (build 1.4.2, J2RE 1.4.2 IBM Windows 32 build cn142-20040926 (JIT ena
    bled: jitc))
    java StringTest 1
    Time in sec: 1.682
    java -version
    java version "1.5.0_05"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_05-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_05-b05, mixed mode)
    java StringTest 1
    Time in sec: 26.588
    java -version
    java version "1.6.0-beta"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.6.0-beta-b59)
    Java HotSpot(TM) Client VM (build 1.6.0-beta-b59, mixed mode, sharing)
    java StringTest 1
    Time in sec: 32.76
    Aaaaaaaaaaaaaaargh!!!

  • String to StringBuffer

    How do i convert String object to StringBuffer object?

    You can initialize a new Stringbuffer to a String
    this way:
    String yourString = "A string";
    StringBuffer sb = new Stringbuffer(yourString);
    Alpha75

  • Problem in retriving string

    Hi all,
    i'm finding problem in retriving string
    i'm getting only first line as output
    the coding is
    import java.io.*;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    class newprg2
    public static void main(String args[]) throws IOException
    InputStream in = new FileInputStream("e:/rag.txt");
    //OutputStream out = newFileOutputStream("e:/rag1.txt");
    int c,pos,pos1;
    String s=new String();
    StringBuffer sb = new StringBuffer();
    while((c=in.read())!=-1)
    sb.insert(0,(char)c);
    sb = sb.reverse();
    s = sb.toString();
    pos = s.indexOf("verify scan_test",0);
    s=s.substring(pos+1);
    while(pos>=0)
    pos=s.indexOf("_cpdp_=",pos);
    pos=s.indexOf("=",pos);
    pos1=s.indexOf(';', pos);
    s=s.substring(pos+1,pos1);
    System.out.println(s);
    }here's the input file
    verify scan_test  {
      Abb {* verify:0  Value:0  lifecycle:0 *}
      W tset_tp;
      S {  _cpdp_=YYYY10YYYYYYYYYYYYYYYYYYY;
      Abb {* Begin loop test *}
      S {  _cpdp_=YYYY10YYYYYYYYYYYYYYYYYYY;
      S {  _cpdp_=YYYY110YY1YYYYYYYYYYYYYYY;
      S {  _cpdp_=YYYY110YY1YYYYYYYYYYYYYYY;
      S {  _cpdp_=YYYY111YY1YYYYYYYYYYYYYYY;
      }now i'm getting output as
    YYYY10YYYYYYYYYYYYYYYYYYY
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
            at java.lang.String.substring(Unknown Source)
            at newprg2.main(newprg2.java:42)but i want output as
    YYYY10YYYYYYYYYYYYYYYYYYY
    YYYY10YYYYYYYYYYYYYYYYYYY
    YYYY110YY1YYYYYYYYYYYYYYY
    YYYY110YY1YYYYYYYYYYYYYYY
    YYYY111YY1YYYYYYYYYYYYYYY

    Manivel wrote:
    raghavan,
    Alter the code inside the while loop like below, you will get as what you expected.
    while (pos >= 0) {
    s = s.substring(pos + 1);
    pos = s.indexOf("_cpdp_=", pos);
    pos = s.indexOf("=", pos);
    pos1 = s.indexOf(';', pos);
    String ss = s.substring(pos + 1, pos1);
    System.out.println(ss);
    }-ManiI'm sorry, but, if you are simply going to spew out the answer to someones homework, you could at least explain what was wrong (before the code). They don't care in the least, but having read it, they may retain at least some spark of the meaning that the lesson was intended to teach. Like this it's just cut and paste, and who gives a damn. They learn a lot that way, NOT!

  • Is there any String format class available in J2ME?

    Hello,
    I am looking for a Formating class which should format a string. For example ( This is Java SE code):
    int num = 999;
                String str = " is my lucky number.";
                String s = String.Format("The Number : %d %s", num, str);I could not find any formatter class nor any direct api from String/StringBuffer class to format a string.
    Any suggestion on this is highly appreciated.
    Thank You.
    Regards,
    DK

    sojourner_jdk wrote:
    Hi DarrylBurke,
    You are right. Its not "Format". String has "format" function ..
    String s = String.format("The Number : %d %s", num, str);Is there such class/api in J2ME?
    Thanks,
    Regards,
    -DKIn J2ME MIDP, [String has no "format" function|http://java.sun.com/javame/reference/apis/jsr118/java/lang/String.html|javadoc].

  • JDBC:KPRB string size limits-NEED HELP!

    Hello All.
    Please, I need your help.
    I have the problems in Oracle 9.2.0.6 with stored java and jdbc:kprb internal driver.
    I try to put string(more than 32K) into LONG-type field using following java class:
    import oracle.sql.CLOB;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.io.Reader;
    import java.io.CharArrayReader;
    public class LongTest {
    public static void insertLong()
    throws Exception {
    Connection con = DriverManager.getConnection("jdbc:default:connection:");
    //generate large string
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < 100000; i++) {
    stringBuffer.append("qwerty");
    String st = stringBuffer.toString();
    //put large string to long-type field
    PreparedStatement pst = null;
    try {
    pst = con.prepareStatement("insert into TEST_LONG (ldata) values (?)");
    pst.setString(1, st);
    pst.execute();
    } finally {
    if (pst != null) {pst.close();}
    But I get error from jdbc:kprb about limitation of data size for this type(LONG).
    But it works well in oracle 10.2.0.1...
    Has anybody a solution of how to do this in oracle 9.2.0.6???
    thanx!

    Hi,
    THis is a known limitation in the 92 RDBMS solved in 10g.
    Kuassi http://db360.blogspot.com

  • How to remove "\r" from a string

    I have a string, it has "\r" and "\n" eg : "abcde dfs \r \n acdsa \r\ncdaacdla"
    when I display this on a panel or print from panel, a box appears at the end, I think its because of \r characters.
    Is there any easy way to remove them.?
    please help thanks.

    sorry i dont which other replace you are talking
    about....btw i am using 1.3.xDon't worry, you'll evolve someday ;~)
    Just dump it into a StringBuffer, and page through and delete manually.
    String removeRs(String string)
       StringBuffer b = new StringBuffer(string.length());
       for(int x = 0 ; x < string.length() ; x++)
          if(string.charAt(x) != '\r')
             b.append(string.charAt(x));
       return b.toString();
    }

Maybe you are looking for

  • How to output surround sound with airport express N

    is this possible? I am streaming successfully with airport express, sounds great with no audio dropouts. I have it hardwired to my router and the AX is connected optical to my surround receiver. Music is only played through my fronts. Is there a way

  • GETWA_NOT_ASSIGNED dump

    Hi , i have creatd a new SyncBo, I generated it and replicated but when I try to sicronize it a dump GETWA_NOT_ASSIGNED  is produced. I read in the next thread a posible solution: But i don´t know where I must configure it or if my problem will be so

  • Travel Management - ESS/R3

    Hi Experts, We need to implement Travel Management for one of our clients. I checked in R/3 its integrated with FI/AC.... I wanted to know whether travel management can be implemented in R/3.i.e without ESS... What are its advantages/disadvantages? R

  • SNMP question

    Am I right? (OS: windows): 1) In order to send trap we don't need anything except started SNMP service for windows. 2) In order to get possibility to make queries (polls) to agent I need to install Agent and have EM Grid Control? 3) I don't have any

  • Print a image with the standard pdf-print function

    hello, we have a Web-Template with a query a chart an the company-image. When we want to print the Web-Template with the pdf button, then we get only the query and the chart in the PDF. What can I do, that I get also the image in de PDF-Print-Layout?