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.

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

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

  • Socket and ObjectOutputStream

    I created an ObjectOutputStream from a socket.
    ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
    Is there any way to get the socket from this object sream?

    I agree with u. And also i dont really need the socket once i have created objectstreams from it.
    I have a ServerSocket which creates a socket the moment someone connects to it. From that socket I am creating object streams. After creating the streams I am passing on the values of the streams(both in and out) to a JFrame object which also implements Runnable. The problem is that my in stream is working here but not my out.
    But the in and out works in the calling method. So I wanted to find out what is the IP address to which my OUT in the thread is sending the object.

  • 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()

  • I have problem using ObjectOutputStream with Multi-Thread

    I am writing a network rpg game for the project.
    Because it is a network game, so i use thread to support multi-user.
    When i using the string to store the command, and send to the server,
    it still can work. You can downlod at http://ivebug.tripod.com/new-string.zip
    (You cannot click the link, you must use [save target as] to save the file)
    1. First compile the files then "java ChatServer",
    2. Then you can execute "java ChatClient".
    3. Input the name for username in the textfield and then press 'login button'.
    4. A small square appear in the up-left corner.
    5. Then you can click in the black panel to move the square.
    6. If you want more than one square can be move, go step 2 to step 5 again.
    It seems everthing is work, but i want more extention for future.
    So i change to use object to encapsulate the command.
    However, it can't work. It stops working after create the socket and
    it can can't run to the line to create an ObjectInputStream and ObjectOutputStream. I don't know why. Who can tell me.
    The program using object at http://ivebug.tripod.com/new-object.zip
    (You cannot click the link, you must use [save target as] to save the file)

    Thank you for solve my problem.
    Now, i can send the object though the socket, however new problem occurs.
    The problem is that after i sent the 'login' object to server,
    the client lost the connection.
    The program has lost connection problem : http://ivebug.tripod.com/new-lost.zip

Maybe you are looking for

  • Error in Simple mx Component Styling?

    Like many, I am finding the behavior of CSS namespaces in Flex 4 very frustrating. I have a very simple example which is not working. I hope I'm missing something! I have a SWC with a defaults.css file. The CSS file is setting the style for Alert usi

  • How do i import imovie project into final cut pro

    I movie 08 is seriously lacking titles and transitions, so I want to spruce up my project in final cut pro, but I do not know how to get the project into final cut pro thanks for your help

  • Help with Cleaning up Empty/White Space

    Hi all, I have a site I'm getting ready to complete, but there are a few things bugging me. One of which is the empty space at the bottom of the page. I'm not sure how to address it and wanted to get your opinion on what to do (and how to do it) The

  • Server Issue Today???

    All my dev V18 Newsstand builds have been getting hung on "Updating Library" today. Only issues downloaded prior to today remain visible in an app'sLibrary view. (and it seems possible to update those issues) But any folio pushed up to the Adobe serv

  • Can you believe it I still have CS 5.1... not anymore... Is CS 5.1 should work with OS X Yosemite 10.10?

    Is CS 5.1 should work with OS X Yosemite 10.10? ...probably not and it is time to update the creative suite I guess... How should I update the creative suite?