StringBuffer and CharBuffer

Hello,
I just stumled across some weird behaviour. It seems to be impossible to directly create a StringBuffer from a CharBuffer.
Consider the following code:
FileReader reader = new FileReader(fileName);
CharBuffer chars = CharBuffer.allocate((int) fileSize);
// read complete file
while(reader.read(chars) != 0);
reader.close();
StringBuffer sb = new StringBuffer(chars);This will result in an empty StringBuffer. The reason for this is that StringBuffer uses CharSequence.length() to determine the length of the CharBuffer. However, CharBuffer implements the length method so that it returns the number of remaining bytes, not the bytes already written to the buffer!!! In the example above, the remaining bytes are 0. A work around for this problem is to call
chars.position(0);before creating the StringBuffer. While this is would work in this case, it might not always be a solution.
Is this a broken behaviour on behalf of CharBuffer? I mean it implements the CharSequence interface and thus should also behave like a CharSequence. IMHO, the CharBuffer implementation of the length method plainly contradicts the defintion of CharSequence.length().
Any comments?
Thank you very much
draoi

FileReader reader = new FileReader(fileName);
CharBuffer chars = CharBuffer.allocate((int)
fileSize);
// read complete file
while(reader.read(chars) != 0);
reader.close();
StringBuffer sb = new StringBuffer(chars);This will result in an empty StringBuffer. The reasonHow about using chars.flip() just before creating the StringBuffer. Seems to work for me (but used put instead of read).
Harald.
BioMed Information Extraction: http://www.ebi.ac.uk/Rebholz-srv/whatizit

Similar Messages

  • How do you determine StringBuffer and List capacity?

    hi all,
    I'm curious and would like to post this query that how to determine the StringBuffer and List capacity after read some of the Java Platform performance book. Some of this performance books simply tells number of capacity brieftly without telling what and how does the capacity stand for.
    First, the book mentioned StringBuffer(50). Note, my question is that what is this 50 stand for? 50 Characters? or any. Can someone help me to rectify this?
    Second, List. ArrayList(0.75). And what is this 0.75(by default) stand for? A heap space? Then how many of them? How many objects that can be stored for not to "exceed 0.75"?
    Please help. :)
    regards,
    Elvis
    scjp

    I think the capacity is the CURRENT size of a container. But it is not equal to the number of elements that container currently hold. Just like, a house can have 10 people within, but problably only 3 people at some time. Also, the capacity is not equal to the maximum size, because container can grows automatically.
    For example, a container whose capacity is 50, currently has 30 elements in it. If you add 10 elements more. That is only an addition operation. But if you add 30 elements to it. Then the container first enlarge its capacity according to some arithmetic(a enlarging rate), secondly carry out the addition operation.
    Now that the capacity is the size, it should be a number standing for HOW MANY elements.... In the case of StringBuffer, it should be how many chars; in the case of ArrayList, it should be how many Objects. I do not think 0.75 can stand for a capacity. Prabaly, it was used to describe the enlarging rate when containers need to contain more elements than its current capacity. ( From JDK API, you can see the type of capacity is int ).
    For containers and alike, the questions "how many I can hold" and "how many I am holding", "Do I can enlarge"? are helpful for understanding how it works.

  • StringBuffer and memory issue

    I am having trouble. I have a fairly large string buffer that I use instead of a file. The String Buffer can grow to 5-10 MB.
    When it grows, it seems that the memory of the JVM basically doubles each time.
    To grow the string buffer, I append to it each time, and I have tried making its initial size 1-2 mb for testing purposes.
    Is there some way to prevent the jvm from growing it's memory by 2 X each time? It seems wasteful, and when many users are logged in, 10 mb per 10 users gets to be a lot. Please advise??

    A StringBuffer will indeed double the storage it uses every time an overflow occurs. Given that it has no idea how large its contents will ultimately be, doubling its size on overflow is statistically the best possible approach.
    Seems to me, by choosing a StringBuffer instead of a file, you have considered the memory/speed trade-off and chosen higher speed, higher memory instead of lower speed, lower memory. And isn't it true that the issue is mostly that you are using multi-megabytes of memory, rather than that more megabytes of memory are potentially being wasted? If you are only concerned about the extra allocation that StringBuffer makes, you could call its setLength() method to clean up the waste after it reaches its maximum size.

  • StringBuffer and PreparedStatement

    Does anyone know why prepared statements don't update ? fields when you provide the preparedstatement with a query that is a stringbuffer?
    i.e.
    StringBuffer query = new StringBuffer(500);
    query.append("SELECT * from Customer WHERE CustId = ?");
        try{
                          pstmt = conn.prepareStatement(
                               query.toString()
                    pstmt.setInt(1, 2);
                    result = pstmt.executeQuery();

    Why are you doing this?
    StringBuffer query = new StringBuffer(500);I am doing this before i have to dynmically manipulate the query, i have an array which i have to loop around and keep adding to the query till i get to the end. I cannot do this by simply specifiying the query inside the prepared statmenet paramaeter. The question mark parameters have nothing to do with adding to the query, it works fine if i specify the actual fields CustID = 1; instead of CustID = ?;
    SO my actual point was simply:
    I want to following query inside a string buffer where i can specifiy the paramaeters at a later stage using setInt, setString etc.
    SELECT * from Customer WHERE CustId = ?
    System.out.println(query.toString()); gives:
    SELECT * from Customer WHERE CustId = ?Now the string buffer, I'm specifiy the query reference directly to the preparedsttement i.e. this would be the same if i did conn.preparedStatment(SELECT * FROM CUSTOMER WHERE CustID = ?);
    try{
                          pstmt = conn.prepareStatement(
                               query.toString()
                     );After i use pstmt.setInt(1, 2);
    i get:
    SELECT * from Customer WHERE CustId = ?when it should be:
    SELECT * from Customer WHERE CustId = 2

  • Storing data in Array or StringBuffer and then comparing it to a string

    I want to store some data in a list or an Array (but apparently an Array only holds 10 items?) and then I want to be able to check if myString is equal to any of the posts in the array/list.
    Or if I use a StringBuffer I want to check to see if myString is part of the StringBuffer?
    How do I do this?
    / Elin

    I want to store some data in a list or an Array (but
    apparently an Array only holds 10 items?)Uh, no. Arrays can (theoretically) contain Integer.MAX_VALUE elements.
    and then I want to be able to check if myString is equal to any
    of the posts in the array/list.Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same character sequence), use equals(), e.g. if (str1.equals(str2))...
    Example:String s1 = "foo";
    String s2 = new String("foo");
    System.out.println("s1 == s2: " + (s1 == s2)); // false
    System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus ==
    Or if I use a StringBuffer I want to check to see if
    myString is part of the StringBuffer?See above discussion on .equals().
    How do I do this?
    Here are some other resources to help you get started with Java.
    The Java™ Tutorial - A practical guide for programmers
    Essentials, Part 1, Lesson 1: Compiling & Running a Simple Program
    New to Java Center
    How To Think Like A Computer Scientist
    Introduction to Computer Science using Java
    The Java Developers Almanac 1.4
    JavaRanch: a friendly place for Java greenhorns
    jGuru
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • Parse lines out of a StringBuffer and/or InputStream

    I am loading and parsing a ~40MB text file. I am retrieving this file using the JCraft JSch SFTP library. This has given me no problems so far.
    Since I need to process this file line by line, my first approach was to read a character at a time off the InputStream provided by the SFTP library, collect characters until a new line was reached, then parse the line. This proved to be extremely slow. Now I'm pulling 1024 characters at a time into a byte[] from the stream and pushing that array into a StringBuffer until the end of the stream has been reached. It has sped up considerably, but now I don't know what the best way would be to process the buffer.
    What would be the best way to split off and process every line of this file? It seems redundant to pull the whole thing into a string buffer then parse it again by using charAt() and substring() to find and chop off lines. Reading character by character from the stream works in theory but is much too slow. Trying to parse the byte[] with fragments of lines is impractical and error prone.
    Memory is not an issue since it is running on a dedicated batch server, but speed is important.
    Thank you.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    public class ReadLines {
        public static void readLinesFromInputStream(InputStream is)
             throws IOException {
         BufferedReader reader = new BufferedReader(new InputStreamReader(is),
              1024 * 1024);
         String line;
         while ((line = reader.readLine()) != null) {
             System.out.println(line);
    }Piet

  • StringBuffer and HashSet

    I've been using a HashSet to clear a String[] from duplicates. In the name of optimization I decided to use StringBuffer instead. This, however, made the removing of dublicates not possible. My question is obviously why, but also, is there a significant performance increase in using StringBuffer instead of string in the code below?
    String[] getID() {
          StringBuffer idNr[]; //was string before...
          idNr = getDirectory(); //returns  a StringBuffer[] with values
          int underScoreStart;
          int underScoreEnd;
          for (int i = 0; i < idNr.length; i++) {
             underScoreStart = idNr.indexOf(dataSeparetor) + 1;
    underScoreEnd = idNr[i].lastIndexOf(dataSeparetor);
    idNr[i] = new StringBuffer(idNr[i].substring( underScoreStart, underScoreEnd));
    java.util.HashSet sortSet = new java.util.HashSet();
    for (int i=0; i <idNr.length; i++) {
    sortSet.add(idNr[i]);
    StringBuffer[] array; // was string before
    int arrayIndex = 0;
    array = new StringBuffer[sortSet.size()];
    Iterator i = sortSet.iterator();
    while(i.hasNext()) {
    array[arrayIndex++] = (StringBuffer)i.next();
    System.out.println(array[arrayIndex-1]);
    StringBuffer tmp; //was string before
    for(int j = 0; j < array.length; j++){                           
    for (int l =0; l < (int)array.length -1; l++) {
    if(Integer.valueOf(array[l].toString()).intValue()>Integer.valueOf(array[j].toString()).intValue()) {
    tmp = array[l];
    array[l] = array[l+1];
    array[l+1] = tmp;
    String returnString[] = new String[array.length];
    for (int l=0; l < returnString.length; l++)
    returnString[l] = array[l].toString();
    return returnString;

    Thanx for you reply. I have gone back to using String
    when copying to the hashset and I have also replaced
    my own sorting function with Arrays.sort... The code
    looks as below now.
    Why is there a performance loss when using string
    buffer in the places I've indicated?Mainly because in a number of places String objects are created anyway and then you create StringBuffers copying the content of the String. If these StringBuffers are not used for editing their content then they are wasted space (in addition if you then need to use their String representation you've created yet another String object of the same content again). You also create many array objects which are abandoned - you can reduce this somewhat.
    Here's what I think is a tidier solution returning a List of String objects rather than an array though the array is still trivial.
    List getId() {
      String[] directory = getDirectory();
      Map workingMap = new HashMap();
      // Populate the map with the integer representations and String representations
      for(int count = 0; count < directory.length; count++) {
        int start = directory[count].indexOf(DATA_SEPARATOR) + 1;
        int end = directory[count].lastIndexOf(DATA_SEPARATOR);
        String s = directory[count].substring(start,end);
        Integer i = new Integer(s);
        workingMap.put(i,s);
      // Now we'll sort the keys and extract the values from the Map in order
      List list = new ArrayList(workingMap.keySet());
      Collections.sort(list);
      List results = new ArrayList(list.size());
      for(Iterator iterator = list.iterator(); iterator.hasNext(); ) {
        results.add(workingMap.get(iterator.next()));
      return results;
    }Personally I'd simply return a list of Integer objects and convert back to String only if necessary. In which case the code is very simple.
    List getId() {
      String[] directory = getDirectory();
      Set workingSet = new HashSet();
      for(int count = 0; count < directory.length; count++) {
        int start = directory[count].indexOf(DATA_SEPARATOR) + 1;
        int end = directory[count].lastIndexOf(DATA_SEPARATOR);
        Integer i = new Integer(directory[count].substring(start,end));
        workingSet.add(i);
      List results = new ArrayList(workingSet);
      Collections.sort(results);
      return results;
    }NB: Yes I know SortedMap is available... yet another way to skin a cat.
    Hope this helps
    PS: Don't forget those Dukes...
    Talden

  • StringBuffer and .equals()

    this is my test codes:
    public class Testing
         public static void main(String arg[])
              StringBuffer sb1 = new StringBuffer("test");
              StringBuffer sb2 = new StringBuffer("test");
              if (sb1.equals(sb2))
                   System.out.println("1");
                    System.out.println("End");
    }At runtime, the program only prints out End, without the number 1.
    My question is shouldn't the if-statement is equal to true?
    Doesnt .equals() method compare the content of one object to another object?
    thanks for any explanation
    daffy

    String is deliberately immutable (a value object). This means you can pass it around and share it as a data member in many classes without the danger that one class might change its value and therefore surprise all the other classes sharing it. IOW, you can treat it much like a basic type. StringBuffer is class for the efficient manipulation of String contents. It is mutable, and not really intended to be 'passed around' (i.e. made part of a interface, declared as an argument or return type in a non-private method) or shared by classes. In general, a String is passed to a method, manipulated via StringBuffer, then returned as a new String.

  • StringBuffer and ObjectOutputStream

    I have a question concerning writting a StringBuffer object to a file using ObjectOutputStream (The code snippet is below..). I am merging 2 files together(relatively small files 300 lines). I am storing the merge portion of the 2 files in a StringBuffer. After the merge is done I write this StringBuffer to a file. See code below...
    private void writeToFile()
    try
    ObjectOutputStream outFile = new ObjectOutputStream(new FileOutputStream("Merged.csv"));
    outFile.writeObject(outBuffer.toString()); //outBuffer is a class member
    outFile.flush();
    catch(Exception e)
    e.printStackTrace();
    }//catch
    }//writeToFile
    PROBLEM:
    A snippet of the orginal file that I am reading in:
    Name,GUID,Initial Date,Initial Time,Initial Audit,Last....
    The same line of the merged file that I am writting out:
    ��2openboxs|6openboxes| 'Name,GUID,Initial Date,Initial Time,Initial...
    It is writing out what appears to be junk at the beginning of the file. I did not do any merge at this point. When I print this first line out to the console the junk does not show up?
    If anybody has run in this problem or know what is causing this, then your input would be greatly appreciated.
    Thanks.

    ObjectOuputStream writes a serialized Object to a file. The 'junk' you are seeing is information about the type of object and other things necessary to deserialize the object. You should try reading the API documentation for a class before you start using it. Use the right tool for the job.

  • StringBuffer and letter color

    hi I use
    StringBuffer Wsb = new StringBuffer();
    if (Type1.contains("on"))
    Wsb.append("C1");
    if (Type2.contains("on")){
    if(Wsb.capacity()!=0)
    Wsb.append(",C2");
    else
    Wsb.append("C2");
    } how can I set the color of letter C1, C2 to red, when I use Wsb.append(" <font color="red"> "); I get error

    HJava wrote:
    how can I set the color of letter C1, C2 to red, when I use Wsb.append(" <font color="red"> "); I get errorNot quite sure what you're trying to do.
    If you append as you said, what the compiler sees is two strings with 'red' between them.
    You need to escape the inner quotes in order that they don't terminate the string, viz:
    Wsb.append(" <font color=\"red\"> ");However, even when you get it to work, Wsb will contain
    C1, C2 <font color="red">
    and, even assuming that your spitting it out to some HTML-aware component, that still won't make C1 and C2 come out red.
    Winston

  • StringBuffer and JLabel?

    Is it possible to pass a StringBuffer to a JLabel? If so, how is it done?
    I'm trying to create a calculator - so pressing the a number button will append to a stringbuffer. That stringbuffer will then be part of the JLabel.
    Currently, I have:
    <snip>
              //zero listener
              zero.addActionListener(this);
              zero.addActionListener(
              new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   readoutlabel.setText("not sure"); // this is where the string has to be implemented
                   });</snip>
    I tried putting in a stringbuffer but it didn't seem to work.
    advTHANKSance

    You don't have to memorize the documentation. It does help if you look in it to find information you need. In your case you needed a method that makes a StringBuffer into a String. So, if you look in the documentation you'll find there are three such methods. Two of them are different forms of substring() and the third is toString(). A quick look at their descriptions tells you which one you want.
    By all means ask questions here, but (as you will have noticed) people don't always like being used as a resource for looking things up for you.
    You're new to Java, so quite likely it hadn't occurred to you that you needed a String. So put on your thick skin. A look in the JLabel documentation would have told you that... but we already went there.

  • What is the difference between StringBuffer and StringBuilder objects

    hi ,
    Please tell me what is the difference between stringBuilder and stringBuffer classes ..why stringbuffer classes is used more with multiple threads but not stringBuilder which is faster than stringBuffer objects
    Thanks in advance

    Odd. You answer your own question by paraphrasing the first paragraph of
    StringBuilder's javadoc:
    This class provides an API compatible with StringBuffer, but with no guarantee
    of synchronization. This class is designed for use as a drop-in replacement for
    StringBuffer in places where the string buffer was being used by a single thread
    (as is generally the case). Where possible, it is recommended that this class
    be used in preference to StringBuffer as it will be faster under most
    implementations.
    Do you really have a question?

  • StringBuffer and synchronization issues

    hello folks,
    please help me out with the following:
    private String str;
    private void method_1()
       str = "abc";
       method_2();
       str = "def";
       method_2();
       str = "ghi";
       method_2();
       str = "jkl";
       method_2();
    private void method_2()
       starts a thread, which accesses "str"
       (uses SwingWorker by Sun)
    //and then for testing purposes:
       System.out.println(str);
    output can be sometimes:
    abc
    abc
    ghi
    ghi
    instead of:
    abc
    def
    ghi
    jklthe problem is probalbly that methods 1 and 2 are not "synchronized". help please...

    Try synchronizing the function
    private synchronized void method_2()

  • Drag and drop ????

    hi all.
    i have a quick question about drag and drop.
    is it possible to drag a text file on the windows desktop into a jtextarea of an application, and display the file.??
    thanks for your time.
    Paul

    Yes, I would say it is. You need to add the correct listeners to the Panel that contains the text area, and when the right sort of file comes in, you open it, put the data into a StringBuffer and add that to the text pane. Here's a code snippet:
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    public class MyPanel extends JPanel implements DropTargetListener
      /** drop action has been changed by drop target */
        public void dropActionChanged(DropTargetDragEvent dtde)
            // must implement
        /** dragdrop entered this panel */
        public void dragEnter(DropTargetDragEvent dtde)
            // must implement
        /** dragdrop exited this panel */
        public void dragExit(DropTargetEvent dte)
            // must implement
        /** dragdrop dragging over this panel */
        public void dragOver(DropTargetDragEvent dtde)
            // must implement
        /** dragdrop dropped on this panel */
        public void drop(DropTargetDropEvent dtde)
            Transferable t=dtde.getTransferable();
            try
                DataFlavor[] dataFlavors=t.getTransferDataFlavors();
                dtde.acceptDrop(DnDConstants.ACTION_COPY);
                System.out.println(dataFlavors.length);
                for(int i=0;i<dataFlavors.length;i++)
                    System.out.println(dataFlavors.getRepresentationClass().toString());
    if(dataFlavors[i].getRepresentationClass().equals(Class.forName("java.util.List")))
    java.util.List list=(java.util.List)t.getTransferData(dataFlavors[i]);
    for(int j=0;j<list.size();j++)
    if(m_frame.doLoad(list.get(i).toString()))
    dtde.dropComplete(true);
    return;
    break;
    dtde.dropComplete(true);
    catch(Exception e)
    Messages.javaException(e);
    The line with 'm_frame.doLoad()' is where I've detected a suitable, file, and go off to open it

  • In need of serious JFrame/Stringbuffer Help!

    Basicly, it opens a GUI with a few buttons like "previous, last, first, next, add, exit"
    and i take 3 inputs from the user...from the JTextField. Those values are put in a file and are supposed to be read (i'm assuming that i use stringtokenizer) but right now i'm using stringbuffer to write to a file. I can't get it to write to the next line though.. it writes next to it..
    I'm just hoping that i'm using the correct functions to do this job. Feedback greatly appreciated, i'm really worried about the stringbuffer and having it write the way it should. I didn't do the reading yet.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    public class BookMaintenance extends JFrame
         private JTextField author;
         private JTextField title;
         private JTextField publisher;
         private JButton add;
         private JButton exit;
         private JButton first;
         private JButton previous;
         private JButton next;
         private JButton last;
         private Container container;
              public BookMaintenance()
                   author = new JTextField(10);
                   title = new JTextField(10);
                   publisher = new JTextField(10);
                   add = new JButton("Add");
                   exit = new JButton("Exit");
                   first = new JButton("First");
                   previous = new JButton("Prev");
                   next = new JButton("Next");
                   last = new JButton("Last");
                   last.setSize(30,10);
                   JPanel jPanel1 = new JPanel();
                   jPanel1.add(new JLabel("Title: "));
                   jPanel1.add(title);
                   JPanel jPanel2 = new JPanel();
                   jPanel2.add(new JLabel("Author: "));
                   jPanel2.add(author);
                   JPanel jPanel3 = new JPanel();
                   jPanel3.add(new JLabel("Publisher: "));
                   jPanel3.add(publisher);
                   JPanel jPanel4 = new JPanel();
                   jPanel4.add(first);
                   jPanel4.add(next);
                   jPanel4.add(previous);
                   jPanel4.add(last);
                   JPanel jPanel5 = new JPanel();
                   jPanel5.add(add);
                   jPanel5.add(exit);
                   container = this.getContentPane();
                   GridLayout gLayout = new GridLayout(5,1);
                   container.setLayout(gLayout);
                   container.add(jPanel1);
                   container.add(jPanel2);
                   container.add(jPanel3);
                   container.add(jPanel4);
                   container.add(jPanel5);     
                   ActionListener actionListener = new ButtonListener();
                   first.addActionListener(actionListener);
                   next.addActionListener(actionListener);
                   previous.addActionListener(actionListener);
                   last.addActionListener(actionListener);
                   add.addActionListener(actionListener);
                   exit.addActionListener(actionListener);
    class ButtonListener implements ActionListener
             public void actionPerformed(ActionEvent event)
                 if(event.getSource() == add)
                             StringBuffer stringBuffer = new StringBuffer();
                             stringBuffer.append(title.getText());
                             stringBuffer.append(" ");
                             stringBuffer.append(author.getText());
                             stringBuffer.append(" ");
                             stringBuffer.append(publisher.getText());
                             stringBuffer.append(" ' ");
                             RandomAccessFile randomAccessFile = null;
                                    try
                                    randomAccessFile = new RandomAccessFile("file.txt","rw");
                                            System.out.println(stringBuffer.toString());
                                    randomAccessFile.seek(randomAccessFile.length()); 
                                    randomAccessFile.writeBytes(stringBuffer.toString() );
                                    randomAccessFile.close();
                                            catch(IOException ioe){}
              public static void main(String args[])
            BookMaintenance frame = new BookMaintenance();
            frame.setTitle("Book Maintenance");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 250);
            frame.setVisible(true);
          //  frame.setResizable(false);
    }

    I have, I've tried many different ways.. but it's hard because with your example, you added it by itself.. and i don't know how to change it to take the input from the user instead of what you gave it.
    Lookin at your code.. how would i replace this with input from the user? like add the title, author, publisher in there?
              items = new ArrayList<InventoryItem>();
              items.add(new InventoryItem("Java Programming", "A book about java programming."));
              items.add(new InventoryItem("Monkey Soup", "A delicious Dinner Meal."));
              items.add(new InventoryItem("Red", "My Favorite Color"));
              items.add(new InventoryItem("Light Bulb", "An incandescent miracle."));
              items.add(new InventoryItem("Caleb Payne", "Your god."));
              items.add(new InventoryItem("You", "Caleb's bitch."));Message was edited by:
    DenisK

Maybe you are looking for