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

Similar Messages

  • How to assign to String[] from StringBuffer in a loop?

    Hi all,
    public class Test {
    public String[] getSJ() 
            String[]    jg;
            String[]    jig;
            String[]    tg;
            String[]    result;
            Date startTime;
            StringBuffer buf = new StringBuffer();
            int i;
            int j;
            int k = -1;
    jg = {"g1", "g2"};
    for( i=0; i < jg.length; i++ )
             jig = {"1", "2", "3"};
             for( j=0; i < jig.length; j++, k++ )
                   buf.append( jg[i] ).append( ":" );                                      
                   buf.append( jig[j] ).append( ":" );   
                   buf.append( Date() );    
                   result[k] = buf.toString();
                   buf = null;
    }I want to add to result string array by assigning from buf which is StringBuffer in a loop. But what happens after buf = null??
    Will the added String be gone?
    Or should I just do:
    buf = "";
    and continue with the loop and the string objects will be preserved? But isn't result just an array of references?
    Many thanks,

    I am not sure I understand correctly. Here is a test program (in real program I call APIs from a library which returns String[] for jg and for jig, i.e they are changing in the loop in runtime.
    I tried to put together test program:
    import java.util.*;
    public class Test {
         public void Test() {
    public String[] getSJ()
            String[] jg = {"g1", "g2"};
            String[] jig = {"1", "2", "3"};
            String[]    result = new String[50];
            StringBuffer buf = new StringBuffer();
            int i;
            int j;
            int k = 0;
    for( i=0; i < jg.length; i++ )
             for( j=0; i < jig.length; j++, k++ )
                   buf.append( jg[i] )
                      .append( ":" )
                      .append( jig[j] )
                      .append( ":" )
                      .append( new Date() );
                   result[k] = buf.toString();
                   buf = null;
       return result;
    public static void main( String[] args ) {
        Test   t = new Test();
        String[] res = t.getSJ();
        for( int i=0; i<res.length; i++ ) {
         System.out.println( res[i] );
    }but when I run it fails in this statement:
    buf.append( jg[i] )
                      .append( ":" )
                      .append( jig[j] )
                      .append( ":" )
                      .append( new Date() );Exception in thread main
    java.lang.NullPointerException
    java.lang.String[] Test.getSJ()
    Test.java:24
    void Test.main(java.lang.String[])
    Test.java:38
    Wierd!?
    And if I change to:
    buf.setLength(0);
    then it fails with this error:
    Exception in thread main
    java.lang.ArrayIndexOutOfBoundsException: 3
            java.lang.String[] Test.getSJ()
                    Test.java:24
            void Test.main(java.lang.String[])
                    Test.java:38Also, I would like not to have to allocate like in:
    String[] result = new String[50];
    because I do not know how many different Strings in array will be returned by API. Is it possible to dynamically adjust
    String[] result
    somehow?
    Many thanks,

  • How to write a string a stringbuffer to a text file or read a file?

    I need create a text file if the file is not exist, if exist, I have to append a string or stringbuffer to the file. Basically I am using java server page for our web application. I need send user input into a text file. I am uploading my JSP into a server, and run JSP from server. I wonder if I want to create a file, where this file goes, and how can I specify the path of the file?
    I used: BufferedReader br = new BufferedReader( new FileReader("report.txt"));
    The file report.txt could not be found.
    Please help me, thank you so much

    Try
    File file = new File("report.txt");
    out.println("File name: "+file.getAbsolutePath());in your jsp page, then you will see where it would be placed it you created it.
    You can specify the full path like this:
    File wFile = new File("c:\\temp\\report.txt"); // for windows
    File uFile = new File("/tmp/report.txt"); // for unix/linux
    // or
    File file = new File(myPath, "report.txt"); // where myPath is the path where you want to place report.txt.You can either use a File object or String object in the FileReader constructor..
    If you just want to know if the file exits, then use a file object and call exists() on it, returns true if the file already exist. If you want to create the file if it doesn't exit and append a string, then you don't need to check if it exist first. Just do it like this:
    PrintStream ps = new PrintStream(new FileOutputStream("report.txt", true), true);
    // again you could use a file object instead of a string with the file name
    ps.println("Add this line");
    ps.close();If the file doesn't exist, it will create it for you. The second argument in FileOutputStream means "append", and the second argument in PrintStream means "autoflush" every time you use the println methods (or add a newline '\n').

  • Append string to stringbuffer in same line

    I have stringbuffer in which i append string thiesestring is of variable lengt
    has different value .I want that when i append string to stringbuffer it append
    to same line .I use append method of stringbuffer.But the whole value is not
    in same line it breaks into many line all lines are not of same size.
    Thanks

    Try making the textarea larger and see if it still
    shows on a new line...Textarea width is very large .There are many line break sometimes all lines
    are of different length so there is no issue of word wrap .I check the output
    sometimes it gives newline when it encounter space but not always .there are also spaces in single line .Sometimes it gives new line when it encounter >
    and sometimes it continue in same line after enconter > .
    Thanks

  • What Are the Differences Between String and StringBuffer?

    Both String and StringBuffer are final classes. StringBuffer grows in size dynamically. Could people help to detail other differences between String and StringBuffer?

    String is immutable. In other words, once it is made, the contents of that instance of String cannot be changed (easily). The size and characters cannot be changed, and code can take advantage of this fact to optimize space. Also, once you have a reference to a string, you do not need to worry about it changing at all, so you can eliminate constant tests to verify things such as size in another class that may want to hold onto the string.
    StringBuffer, as you noticed, can change dynamically. While this provides flexibility, it cannot be optimized and assumptions cannot be made as with strings. If a class holds a reference to a StringBuffer that it does not own, there is a possibility that it may change things such as size when the class tries to use it later. StringBuffer is also less efficient in handling space then an equivalent String. The character array to hold a String is exactly the length to hold all the characters. StringBuffer, on the other hand, adds a 16 character buffer of array space for possible expansions. Also, the size of the internal array doubles when its internal capacity is exceeded. So, unless you explicitly maintain the size, a StringBuffer will take up more memory then an equivalent String, and if your program needs thousands of instances of Strings (which is not uncommon), that space can add up.
    I hope this helps clarify some things for you.
    -JBoeing

  • Please simplify - doubt in String and StringBuffer

    in output of StringTest1 StringBuffer take more time than String concatenation using + operator.
    and in output of StringTest2 String concatenation using + operator take more time than StringBuffer
    please simplify..
    public class StringTest1 {
    public static void main(String[] args){
               //Test the String Concatination
              long startTime = System.currentTimeMillis();
              for(int i=0;i<5000;i++){
              String result = "This is"+ "testing the"+ "difference"+ "between"+
                                    "String"+ "and"+ "StringBuffer";
              long endTime = System.currentTimeMillis();
              System.out.println("Time taken for string concatenation using + operator : "
                                              + (endTime - startTime)+ " milli seconds");
               //Test the StringBuffer Concatination
               long startTime1 = System.currentTimeMillis();
               for(int i=0;i<5000;i++){
              StringBuffer result = new StringBuffer();
                                 result.append("This is");
                                result.append("testing the");
                                result.append("difference");
                                result.append("between");
                               result.append("String");
                               result.append("and");
                               result.append("StringBuffer");
              long endTime1 = System.currentTimeMillis();
              System.out.println("Time taken for String concatenation using StringBuffer : "
                                                 + (endTime1 - startTime1)+ " milli seconds");
    }output:
    Time taken for String concatenation using + operator : 0 milli seconds
    Time taken for String concatenation using StringBuffer : 15 milli seconds
    public class StringTest2 {
    public static void main(String[] args){
              //Test the String Concatenation using + operator
              long startTime = System.currentTimeMillis();
              String result = "hello";
              for(int i=0;i<1500;i++){
              result += "hello";
              long endTime = System.currentTimeMillis();
              System.out.println("Time taken for string concatenation using + operator : "
                                              + (endTime - startTime)+ " milli seconds");
              //Test the String Concatenation using StringBuffer
              long startTime1 = System.currentTimeMillis();
              StringBuffer result1 = new StringBuffer("hello");
              for(int i=0;i<1500;i++){
              result1.append("hello");
              long endTime1 = System.currentTimeMillis();
              System.out.println("Time taken for string concatenation using StringBuffer :  "
                                              + (endTime1 - startTime1)+ " milli seconds");
    }output:
    Time taken for string concatenation using + operator : 63 milli seconds
    Time taken for String concatenation using StringBuffer : 0 milli seconds

    As jverd said - in the first class, your String concat is only done once. Add/replace this code to your original and see what you get"
    {code} String results = "This is"+ "testing the"+ "difference"+ "between"+
    "String"+ "and"+ "StringBuffer";
    Object o = results;
    for(int i=0;i<500000;i++){
    results = "This is"+ "testing the"+ "difference"+ "between"+
    "String"+ "and"+ "StringBuffer";
    if (i < 10 ) System.out.println("same result: "+(o == results));
    }{code}
    Now made just one change ( appending +i to that String each time ) as follows:
    {code} String results = "This is"+ "testing the"+ "difference"+ "between"+
    "String"+ "and"+ "StringBuffer";
    Object o = results;
    for(int i=0;i<500000;i++){
    results = "This is"+ "testing the"+ "difference"+ "between"+
    "String"+ "and"+ "StringBuffer"+i;
    if (i < 10 ) System.out.println("same result: "+(o == results));
    {code}
    Then, also in the first class, create your StringBuffer BEFORE the loop and "delete(0,result.length());" within the loop. This speeds it up and makes for a better comparison.
    Next, increase your loop size to something that will produce more consistent results (I used half a million).
    Lastly (or approximately so, at least) change the first part of your first class - using String - to the following:
    {code} results = "This is";
    results += "testing the";
    results += "difference";
    results += "between";
    results += "String";
    results += "and";
    results += "StringBuffer";
    results += i;
    {code}
    Now you have a more legitimate comparison and you will see a real difference.

  • 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/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...

  • 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.

  • StringBuffer vs. String

    Hi,
    I wonder how StringBuffer compares in memusage minimization and performance to String. I am processing a lot of strings, mostly by shortening them, but sometimes also by replacing a char. Right my implementation is by = aStr.substring(..); sometimes followed by a .concat(..);
    If i change String to StringBuffer, will the system get the memory of the discarded portion of the String above back? If the StringBuffer's length needs to be increased, how is that implemented? By making a new pointer and returning the previous memory back to the system?
    In short, will i lose or gain any memory by using StringBuffer instead String? Any tips on performance also appreciated.
    Reshat.

    So, i will not lose any memory using StringBufferinstead String, right?
    Memory is not an issue. A StringBuffer is more
    efficient when you need to change the value of'text'.
    A String is more efficient for a constant 'text'
    value.
    Once again memory is not an issue.Well, I'd say the memory is an issue. The efficiency
    you mentioned mainly comes from memory related issues
    as Java with its VM is awfully slow with memory
    management. You'll do always faster the less you have
    memory related issues in your program.Old topic...
    And the answer is really still the same. String is intended for a specific use. StringBuffer is intended for a different use. The performance benifits come from properly using each. This is due to the way that the compiler handles each one in expressions and the code (not memory) that is involved in that.
    Both of them internally use a char array, so the actual memory used is irrelevant.
    To delve more deeply into this you might want to look at the source code for both classes and spend some time looking at the byte code output (see javap) to see how they are used.

  • 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!!!

  • Converting a text file into a String

    I need to convert a text file (in whatever format, in my case it would be xml and xsl files) in a String.
    I made this methods:
    public static String createStringFromFile(File f) {
            StringBuffer buf = new StringBuffer();
            try {
                FileInputStream fInp = new FileInputStream(f);
                byte[] byteArray = new byte[fInp.available()];
                int bLetti = fInp.read(byteArray);  
                if (bLetti == fInp.available()) {
                    for (int i=0; i<fInp.available(); i++)
                        buf.append(Byte.toString(byteArray));
    else
    throw (new IOException("Errore nella lettura del file"));
    fInp.close();
    } catch (Exception e) {
    ErrorManager.getError(e);
    return (buf.toString());
    public static String createStringFromFile(String fileName) {
    StringBuffer buf = new StringBuffer();
    try {
    FileInputStream fInp = new FileInputStream(fileName);
    byte[] byteArray = new byte[fInp.available()];
    int bLetti = fInp.read(byteArray);
    if (bLetti == fInp.available()) {
    for (int i=0; i<fInp.available(); i++)
    buf.append(Byte.toString(byteArray[i]));
    else
    throw (new IOException("Errore nella lettura del file"));
    fInp.close();
    } catch (Exception e) {
    ErrorManager.getError(e);
    return (buf.toString());
    There are no compilation or runtime errors, but the result string is empty. Not null, empty. What should I do? :)

    Do you really want to use bytes and so on when java does it all for you?
    Here's how I did it, hope it's useful.
    public String getFileAsString(String fileName){
         StringBuffer buffer = new StringBuffer();
         try{
         BufferedReader bRead = new BufferedReader(new FileReader(new File(fileName)));
         String str = "";
         while( (str = bRead.readLine()) != null ){
              buffer.append(str);
         }//end while
         bRead.close();
         }catch(Exception e){
         System.err.println("in getFileAsString(): " + e.toString());
         }//end try
         return buffer.toString();
    }//end getAsString()

  • Problem with code: reading a string

    Hi,
    I am very new to java so excuse my naivety. i need to write some code which will decode an encrypted message. the message is stored as a string which is a series of integers which. Eg. Nick in this code is 1409030110 where a = 1, b = 2,... and there is a 0 (zero) after every word. at the moment the code only goes as far as seperating the individual characters in the message up and printing them out onscreen.
    Heres the code:
    int index = 0;
    while(index < line.length() - 1) {
    char first = line.charAt(index);
    char second = line.charAt(index + 1);
    if(second == 0) {
    char third = line.charAt(index + 2);
    if(third == 0) {
    System.out.print(first + "" + second);
    index = index + 3;
    else {
    System.out.print(first);
    index = index + 2;
    else {
    System.out.print(first + "" + second);
    index = index + 3;
    Basically its meant to undo the code by reading the first two characters in the string then determining whether the second is equal to 0 (zero). if the second is 0 then it needs to decide whether the third character is 0 (zero) because the code could be displaying 10 or 20. if so the first two characters are recorded to another string and if not only the first is recorded. obviously if the second character is not a zero then the code will automatically record the first 2 characters.
    my problem is that the code doesnt seem to recognise the 0 (zero) values. when i run it thru with the string being the coded version of Nick above (1409030110) the outputted answer is 1490010 when it should be 149311. as far as i can see the code is right but its not working! basically the zeros are begin removed but i need each group of non-zero digits to be removed seperately so i can decode them.
    if anyone has understood any of this could you give me some advice, im at my wits end!
    Thanks, Nick

    Try something like this:
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.IOException;
    import java.util.Properties;
    public class SimpleDecoder
        /** Default mapping file */
        public static final String DEFAULT_MAPPING_FILE = "SimpleDecoder.properties";
        /** Regular expression pattern to match one or more zeroes */
        public static final String SEPARATOR = "0+";
        private Properties decodeMapping = new Properties();
        public static void main(String [] args)
            try
                SimpleDecoder decoder = new SimpleDecoder();
                decoder.setDecodeMapping(new FileInputStream(DEFAULT_MAPPING_FILE));
                for (int i = 0; i < args.length; ++i)
                    System.out.println("Original encoded string: " + args);
    System.out.println("Decoded string : " + decoder.decode(args[i]));
    catch (Exception e)
    e.printStackTrace();
    public void setDecodeMapping(InputStream stream) throws IOException
    this.decodeMapping.load(stream);
    public String decode(final String encodedString)
    StringBuffer value = new StringBuffer();
    String [] tokens = encodedString.split(SEPARATOR);
    for (int i = 0; i < tokens.length; ++i)
    value.append(this.decodeMapping.getProperty(tokens[i]));
    return value.toString();
    I gave your "1409030110" string on the command line and got back "nick". The SimpleDecoder.properties file had 26 lines in it:
    1 = a
    2 = b
    3 = c
    // etc;Not a very tricky encryption scheme, but it's what you asked for. - MOD

  • How to get an XML string from a Java Bean without wrting to a file first ?

    I know we can save a Java Bean to an XML file with XMLEncoder and then read it back with XMLDecoder.
    But how can I get an XML string of a Java Bean without writing to a file first ?
    For instance :
    My_Class A_Class = new My_Class("a",1,2,"Z", ...);
    String XML_String_Of_The_Class = an XML representation of A_Class ?
    Of course I can save it to a file with XMLEncoder, and read it in using XMLDecoder, then delete the file, I wonder if it is possible to skip all that and get the XML string directly ?
    Frank

    I think so too, but I am trying to send the object to a servlet as shown below, since I don't know how to send an object to a servlet, I can only turn it into a string and reconstruct it back to an object on the server side after receiving it :
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class Servlet_Message        // Send a message to an HTTP servlet. The protocol is a GET or POST request with a URLEncoded string holding the arguments sent as name=value pairs.
      public static int GET=0;
      public static int POST=1;
      private URL servlet;
      // the URL of the servlet to send messages to
      public Servlet_Message(URL servlet) { this.servlet=servlet; }
      public String sendMessage(Properties args) throws IOException { return sendMessage(args,POST); }
      // Send the request. Return the input stream with the response if the request succeeds.
      // @param args the arguments to send to the servlet
      // @param method GET or POST
      // @exception IOException if error sending request
      // @return the response from the servlet to this message
      public String sendMessage(Properties args,int method) throws IOException
        String Input_Line;
        StringBuffer Result_Buf=new StringBuffer();
        // Set this up any way you want -- POST can be used for all calls, but request headers
        // cannot be set in JDK 1.0.2 so the query string still must be used to pass arguments.
        if (method==GET)
          URL url=new URL(servlet.toExternalForm()+"?"+toEncodedString(args));
          BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
        else     
          URLConnection conn=servlet.openConnection();
          conn.setDoInput(true);
          conn.setDoOutput(true);           
          conn.setUseCaches(false);
          // Work around a Netscape bug
          conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
          // POST the request data (html form encoded)
          DataOutputStream out=new DataOutputStream(conn.getOutputStream());
          if (args!=null && args.size()>0)
            out.writeBytes(toEncodedString(args));
    //        System.out.println("ServletMessage args: "+args);
    //        System.out.println("ServletMessage toEncString args: "+toEncodedString(args));     
          BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
          out.flush();
          out.close(); // ESSENTIAL for this to work!          
        return Result_Buf.toString();               // Read the POST response data   
      // Encode the arguments in the property set as a URL-encoded string. Multiple name=value pairs are separated by ampersands.
      // @return the URLEncoded string with name=value pairs
      public String toEncodedString(Properties args)
        StringBuffer sb=new StringBuffer();
        if (args!=null)
          String sep="";
          Enumeration names=args.propertyNames();
          while (names.hasMoreElements())
            String name=(String)names.nextElement();
            try { sb.append(sep+URLEncoder.encode(name,"UTF-8")+"="+URLEncoder.encode(args.getProperty(name),"UTF-8")); }
    //        try { sb.append(sep+URLEncoder.encode(name,"UTF-16")+"="+URLEncoder.encode(args.getProperty(name),"UTF-16")); }
            catch (UnsupportedEncodingException e) { System.out.println(e); }
            sep="&";
        return sb.toString();
    }As shown above the servlet need to encode a string.
    Now my question becomes :
    <1> Is it possible to send an object to a servlet, if so how ? And at the receiving end how to get it back to an object ?
    <2> If it can't be done, how can I be sure to encode the string in the right format to send it over to the servlet ?
    Frank

  • Apostrophe in a String bombs a SQL insert

    I am having an issue with a Customer String parameter that is being used in a SQL INSERT. The customer name may from time to time have an apostrophe in it that causes our SQL INSERT to bomb on a missing comma error. I have tried to do this two separate ways:
    1)
    String query = "INSERT into CUSTOMER VALUES(" + account[0].custAcctNbr + ",'" + account[0].companyNm + "'," +
                   "'IN',null," + salesPerson[0].salespersonID + "," + "null,null,null,null,null," +
                   "null,null,null,null,null,null,null,null,null)";
    This works until an apostrophe is in the companyNm varaiable.
    2)
         PreparedStatement insertCustomer = bcc_conn_cust.prepareStatement(
         "INSERT into CUSTOMER VALUES(?,?,?,null,?,null,null,null,null,null,null,null,null,null,null,null,null,null,null");
         insertCustomer.setInt(1,Integer.parseInt(account[0].custAcctNbr));
         insertCustomer.setString(2,account[0].companyNm);
         insertCustomer.setString(3,"IN");
         insertCustomer.setInt(4,salesPerson[0].salespersonID);
         insertCustomer.executeUpdate();
    This also works when there is no apostrophe. However both bomb when it is present. Is there anyway to get around this, short of parsing a company name every single time we insert a new customer?

    Do you have any idea why this is not working? yes, whatever driver you are using isn't implementing this properly.
    variable I am using is a String variable, that has a
    value of Bates' Brownies. According to all I read, it
    seems I have used the Prepared Statement correctly but
    it is giving me that missing comma error. I would
    really rather not have to search every single company
    name as it is entered.well unless you can either find another driver or fix the one you've
    got i can't see what else you can do...
    here is some code to help you along with that.
    private String replaceQuotes(String toReplace){
      StringBuffer buff = new StringBuffer(toReplace);
      for(int i=0;i<buff.length();i++){
        if(buff.charAt(i)=='\''){
          buff.insert(i,'\'');
          i++;
      return buff.toString();

Maybe you are looking for

  • Upload/Download from unix - give easy exammple for tab delimited .TXT file

    Hello experts, I have 2 requirements. 1. I want to upload a tab delimited .txt file from local PC to UNIX server. 2. I want to Read same file, then some process and get result to the same location. (output file name should be diffrent) How i can fulf

  • Plugin updates will not stop appearing when firefox is opened. have done updates but does not see Adobe update. How do I fix this

    When I open firefox plugin update page appears ,I have done all updates it wanted, but it does not see the Adobe update as being done. adobe is current as per there site. How do I stop or turn off this problem?

  • Office 365 home premium

    Hi I have an Offoce 365 Home Premium Skype subscription. It used to include landlines and cellphones. Now I just get landlines. Has the policy changed, or must I do something? I am in South Africa, which is a supported country. Thanks  richstad

  • Where is the firewall rules file??

    I had to tweak a bunch of firewall rules following this latest Apple security update (it broke my mail services). In the log (G5 Xserve running 10.4.11), it now says "mail servermgrd_ipfilter:ipfw config:Error:Failure code returned by ipfw command: 6

  • Bridge CS5 previews not updating?

    I recently upgraded to CS5, and now I'm tearing my hair out.  It's the first version for me that does not update a preview after I've made adjustments to the raw image.  I've looked through preferences and don't see anything to check or uncheck.  Rig