UTFDataFormatException on Serialized File

I'm trying to update a sequential-access file (created with ObjectOutputStream and the like). To update an object, I'm copying the whole file to a temporary file, then copying back 1 object at a time, replacing the one to be updated with the updated one. Here's my (edited) code:
while ( fileInputStream.available() > 0 )
    tempObject = ( MyObject )objectInputStream.readObject();
    if ( tempObject.getIDNumber() == updateObject.getIDNumber() )
        objectOutputStream.writeObject( updateObject );
        objectOutputStream.flush();
    else
        objectOutputStream.writeObject( tempObject );
        objectOutputStream.flush();
}fileInputStream is a FileInputStream associated with the temporary file.
MyObject is obviously the object I'm using; "getIDNumber()" is the method that lets me figure out which one I'm supposed to update.
objectOutputStream is an ObjectOutputStream associated with the "real" (non-temp) file.
In practice, I can run this update once, and it gives no errors. But, if I try to run it again, it throws a UTFDataFormatException on the tempObject = ( MyObject )objectInputStream.readObject();line, leading me to believe something with the output is wrong. Any ideas?

UTFDataFormatException occurs when you try to read in a String variable more than 64k. Thats the serialization limit.

Similar Messages

  • Reading data from a serialized file(Data is in special characters &symbols)

    Please help me.... I struck up at reading data in a serialized file. It is a text file with some special characters. My question is - Is it a real serialized file or some bad file? If it a real good one please tell me which method i have to use to read? Actually i have to read records with time stamps from this file and have to do some calculations on them.
    FILE CONTENTS :
    ¬í sr java.util.ArrayListxÒ^TM^Ça I sizexp w sr *com.progress.recruitment.test.email.Record¨ƒù~‹6 I aI bI cI dI idI timexp                  sq ~                      ¥¤sq ~            
    Ûsq ~ gÒsq ~ 5ásq ~ E.x

    It looks like it might contain serialized Java objects, since it contains Java class names. Have you tried reading it as such to see what happens?
    Or are you asking how to do that? In which case why not just start with the code in the Java serialization tutorial and go from there?
    Or did you not know there was such a tutorial? Google keywords: "java serialization tutorial".

  • What is a serialized file?

    Hi all!
    I googled, but I seem to only be able to find out methods involving a serialized file, but I can't find out exactly what it is to start with. Any explanations/links welcome.
    Thanks!

    java.io.Serializable
    java.io.ObjectOutputStream
    java.io.FileOutputStream
    (API Docs)
    - Saish

  • Serial File to make it a Full Version

    Hi Experts,
    I was wondering if the Serial file the only thing we need to make this STVN 2.1 Orgchart .NET a full version?  Right now, it says Soft Demo as the version we have. 
    Thanks,
    Michael Dinh

    Hi Michael,
    No need to uninstall from Production, it's just that legally the demo licence you had in place ("soft licence") is not valid in Production. All you need to do is put your licence file into the XML folder in each environment (DEV, QAS and PRD) and restarted the application instance (either via an IIS reset or NW CE instance restart).
    Good luck!
    Luke

  • Manipulate a object serialized file when the .class file is missing

    I want to know if it is possible to recovery the object when its class file is missing! I guess it needs to manipulate the file and extract the values and ask user to name the values, after that, create a new class file for future use. However, I don't know how to manipulate the object serialized file. I really appreciate any hints you guys can give

    I suppose if you created the class file, with the same name, package, and unique serial ID, fields, etc, it can be done.
    Another option is to not use serialization if you are just trying to recover the data. Again you would need to know what the datatypes of the fields are to know what it is you are trying to read, how to parse serialized data, etc. Some Objects are easy to read, like Strings. The more complicated ones are the simple datatypes.

  • Serials files issue

    Hi Expert,
    I would like to ask that i have deployed Nakisa .SCA file on SAP CE 7.2. I am able to login on http://host/CareerPlanning/managet.jsp,but i go to /XML fodler and upload few XML files then they are created one serial file.
    I close the browser and restart the application system but again it is asking for same thing USER and Password(admin/admin)
    when i put the user and password again same thing upload TAB mentioning "serials files is already existed.
    I am unable to open page where i can see the lots of option to configure Nakisa
    Does the correct serial files  i am uploading or Nakisa provided Serials files seperatly?

    The URL ending ../manager.jsp is for the Administrator Console and the default login is always admin / admin (once logged in you can change this via the Security Settings section.
    You will need to complete some basic configuration (e.g. connection strings) before you publish your changes and then are able to use the CareerPlanning application
    To run the CareerPlanning application, use the same URL but change /manager.jsp to /default.jsp
    The serial file is needed (in the XML directory) to be able to use the applications.
    Stephen

  • Accessing Serialized Files randomly.

    I have a problem accessing serailized files randomly. I am using ObjectOutputStream to write objects to a file. I am using the ObjectInputStream to read the objects from the file. Both of these work fine if the order in which i Write objects is the same as the order in which I read Objects. But I need to skip few objects when reading objects from the file. I know API states that the order of writing and reading should be the same. But still is there any way where i can read serailized objects ramdomly form the file.
    Please help me with this it is very impritant of the project. We are trying to store tuples in the file. We are going to build an index over these tuples and then read the tuple that we need.
    Thankyou,
    Nishant

    You could wrap the ObjectOutputStream around a ByteArrayOutputStream to first serialize an object to a byte[] and then save that into a RandomAccessFile.
    The trick is to be able to tell where in the file each serialized object starts. Possibilities include:
    1) If your objects are known to serialize to a fixed size (or if there is a reasonable max size of the serialized object), you could pad each byte[] "record" you write to the file (eg, each object always uses 1K bytes). Then you can easily read back the i'th object byte[] and deserialize it.
    2) Design into your RandomAccessFile a "directory" section that keeps track of each stored object and it's starting byte address in the file.
    If the file needs to hold an arbitrary # of objects, the directory could support a special entry pointing to a "next" directory section later in the file.
    -Brian

  • Can't upload serial file for Orgchart

    Hi,
    I was trying to open the http://sapnkd:50000/OrgChart/manager.jsp page inorder to applly the serial key and I am getting
    Error: Application error occurred during the request processing.
      Error occurred in invoking event "contextInitialized()" on listener class com.sun.faces.config.ConfigureListener.
      SAP Technology Troubleshooting Guide
    Details: WebApplicationException log ID is [00505691005A004A00000003000013E0
    But I was able to apply the key for SuccessionPlanning. I followed the instructions as suggested in the guide like enableing relative URLS but still getting the same message.
    Please advice us.
    Thanks
    Pradeep.G

    Hi , I found the belwo information in default trace log.
    I could see that all components of Nakisa are showing Green and started in the portal. Please advice.
    #2.0 #2011 08 12 09:57:32:920#0-400#Error#com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl#
    com.sap.ASJ.web.000137##Nakisa/OrgChart#00505691005A006600000002000013E0#7528850000000004#Nakisa/OrgChart#com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl#J2EE_GST_NKD#0##04D76990C4EB11E09BB500000072E192#04d76990c4eb11e09bb500000072e192#04d76990c4eb11e09bb500000072e192#0#Thread[HTTP Worker [@1351286997],5,Dedicated_Application_Thread]#Plain##
    Cannot process an HTTP request to servlet [org.apache.jsp.manager_jsp] in [OrgChart] web application.
    For more details on the problem please check traces searching by logId: 00505691005A006600000000000013E0#
    #2.0 #2011 08 12 09:57:32:921#0-400#Error#com.sap.engine.services.servlets_jsp.ISE500#
    com.sap.ASJ.web.000500##Nakisa/OrgChart#00505691005A006600000003000013E0#7528850000000004#Nakisa/OrgChart#com.sap.engine.services.servlets_jsp.ISE500#J2EE_GST_NKD#0##04D76990C4EB11E09BB500000072E192#04d76990c4eb11e09bb500000072e192#04d76990c4eb11e09bb500000072e192#0#Thread[HTTP Worker [@1351286997],5,Dedicated_Application_Thread]#Plain##
    500 Internal Server Error is returned for HTTP request [http://sapnkd.carmeusesap01.com:50000/OrgChart/manager.jsp]:
      component [org.apache.jsp.manager_jsp],
      web module [OrgChart],
      application [Nakisa/OrgChart],
      DC name [Nakisa/OrgChart],
      CSN component[],
      problem categorization [com.sap.ASJ.web.000137],
      internal categorization [-631873009].
    [EXCEPTION]
    com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED! DTD factory class org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl does not extend from DTDDVFactory.
         at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:213)
         at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:196)
         at com.sap.engine.services.servlets_jsp.server.application.WebEvents.contextInitialized(WebEvents.java:87)
         at com.sap.engine.services.servlets_jsp.server.deploy.ApplicationThreadInitializer.run(ApplicationThreadInitializer.java:265)
         at com.sap.engine.services.deploy.server.utils.concurrent.impl.CleanRunnable.run(CleanRunnable.java:56)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:182)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:299)
    Caused by: org.apache.xerces.impl.dv.DVFactoryException: DTD factory class org.apache.xerces.impl.dv.dtd.DTDDVFactoryImpl does not extend from DTDDVFactory.
         at org.apache.xerces.impl.dv.DTDDVFactory.getInstance(Unknown Source)
         at org.apache.xerces.impl.dv.DTDDVFactory.getInstance(Unknown Source)
         at org.apache.xerces.impl.xs.opti.SchemaParsingConfig.<init>(Unknown Source)
         at org.apache.xerces.impl.xs.opti.SchemaParsingConfig.<init>(Unknown Source)
         at org.apache.xerces.impl.xs.traversers.XSDHandler.<init>(Unknown Source)
         at org.apache.xerces.impl.xs.traversers.XSDHandler.<init>(Unknown Source)
         at org.apache.xerces.impl.xs.XMLSchemaLoader.<init>(Unknown Source)
         at org.apache.xerces.impl.xs.XMLSchemaLoader.<init>(Unknown Source)
         at org.apache.xerces.impl.xs.XMLSchemaValidator.<init>(Unknown Source)
         at org.apache.xerces.jaxp.validation.XMLSchemaValidatorComponentManager.<init>(Unknown Source)
         at org.apache.xerces.jaxp.validation.ValidatorHandlerImpl.<init>(Unknown Source)
         at org.apache.xerces.jaxp.validation.AbstractXMLSchema.newValidatorHandler(Unknown Source)
         at org.apache.xerces.jaxp.DocumentBuilderImpl.<init>(Unknown Source)
         at org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(Unknown Source)
         at com.sun.faces.config.ConfigManager$ParseTask.getBuilderForSchema(ConfigManager.java:501)
         at com.sun.faces.config.ConfigManager$ParseTask.getDocument(ConfigManager.java:433)
         at com.sun.faces.config.ConfigManager$ParseTask.call(ConfigManager.java:394)
         at com.sun.faces.config.ConfigManager$ParseTask.call(ConfigManager.java:351)
         at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
         at java.util.concurrent.FutureTask.run(FutureTask.java:138)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
         at java.lang.Thread.run(Thread.java:679)
    Thanks
    Pradeep.G

  • Serial File Access

    I'm trying to make a program that can write into a specific line in a text file, however I'm facing the problem that I can only write to the first line. Is there something similar in the print function as in the read function, that you can read or write blanks until you're at the desired line? Could there be another solution to my problem?

    Or, if you're just wanting x number of blank lines before you begin writing, use a for loop and write the desired number of line separators.
    Example (untested):
    BufferedWriter out = new BufferedWriter(new FileWriter(yourfileName));
    for (int j = 0; j < 10; j++) {
        out.newLine();
    out.close();

  • Read data from Vector object serialized in a file issue!!

    Hi all,
    I have two classes :CBase and CHelper class in a package and serializing some information in a file and then reading it. I am facing some problem while reading the data
    which was stored using vector of objects. Below is the detailed problem:::::
    ////////////CHELPER
    public class CHelper implements Externalizable, Cloneable {
    public string szname;
    //..other functions writeexternal read external
    ////////////CBASE
    public class CBase
    implements Externalizable, Cloneable {
    protected boolean bRead;
    protected boolean bWrite;
    protected Vector vData;
    public void addInstance(CHelper obj) {
    vData.addElement(obj);
    //..other functions writeexternal read external
    I am Serializing all the CBase information in a file and trying to read the contents from this serialized file::::
    CBase base = new CBase();
    CHelper obj = new CHelper();
    obj.setName("HELPER");
    base.addInstance(obj); // ADDING THE OBJECT DATA INTO THE VECTOR
    base.bRead = true;
    base.bWrite = true;
    // Writing to the file
    FileOutputStream fs = new FileOutputStream("d:\\temp\\Base.txt");
    ObjectOutputStream os = new ObjectOutputStream(fs);
    os.writeObject(base);
    os.close();
    //reading from the file
    FileInputStream fi = new FileInputStream("d:\\temp\\Base.txt");
    ObjectInputStream oi = new ObjectInputStream(fi);
    CBase read = (CBase) oi.readObject();
    PRINTING THE OUTPUT
    System.out.println("Vector = " + read.vData.firstElement().toString());
    System.out.println("Write = " + read.bRead);
    System.out.println("Read = " + read.bWrite);
    The output is something like:
    Vector = com.sp.CHelper@14b7453 // WHAT IS THIS ?? GARBAGE ?? NOT ABLE TO ANALYSE :(
    Write = true;
    Read = true;************
    MY PROBLEM:
    i.e How to get the information stored in the Vector ? I am getting something "com.sp.CHelper@14b7453 " whereas the expected output should be Vector = HELPER. I am
    writing and reading the vector as follows:
    // CHELPER
    public void writeExternal(ObjectOutput out) throws IOException {
    out.writeUTF(szName.toString());
    public void readExternal(ObjectInput in) throws IOException,
    ClassNotFoundException {
    setName(in.readUTF());
    Externalize in CBase Classs
    out.writeInt(getInstanceCount()); // getting number of objects in the vector
    for (int index = 0; index < getInstanceCount(); index++) {
    out.writeObject((CHelper)vData.get(index));
    out.writeBoolean(bWrite);
    out.writeBoolean(bRead);
    And reading like this::
    int iNumberofInstances; // number of instances
    iNumberofInstances = in.readInt();
    vData.clear();
    // Get the CHelper object and add it into the CFeatureBase vector
    for (int i = 0; i < iNumberofInstances; i++) {
    CHelper objbase = (CHelper)in.readObject();
    vData.add(objbase);
    this.bWrite = in.readBoolean();
    this.bRead = in.readBoolean();
    I suppose that i am correctly WRITING AND READING the data. B/w what can be the problem. All suggestions are welcome/
    Thanks,
    Rohit

    Vector = com.sp.CHelper@14b7453 // WHAT IS THIS ??
    GARBAGE ?? NOT ABLE TO ANALYSE :(
    Write = true;
    Read = true;************
    MY PROBLEM:
    i.e How to get the information stored in the Vector
    ? I am getting something "com.sp.CHelper@14b7453 "
    whereas the expected output should be Vector =
    HELPER.This is perfectly normal behaviour if your CHelper class doesn't override the toString() method. The default toString() method in Object just prints the name of the class and a hex representation of the object's hash code.
    Add a toString() method to CHelper that returns szname and you should see what you are expecting.

  • Changing serialVersionUID  of  objects serialized in a file.

    For myResearch project I have created an application that saves it's data by placing its objects in an ArrayList and then serializing the ArrayList to file.
    Up untill now it has been going swimmingly over 18 months. However, I am now for seemingly no reason encountering versioning errors when my app tries to de-serialise the objects. This happens for classes that I have not modified in any way.
    I know now that I should manually set the serialVersionUID of my objects to overcome this in the future.
    However, my core quesion is:
    Can I change the serialVersionUID of the objects in the ArrayList of the serialized file. Otherwise I have to rebuild over 100 program save files.
    Kind Regards,
    Andrew.

    They all have serialVersionUID like
    -6011647393756382469
    You suggestion will not be a very elegent solution,
    as the numbers are meaningless.I do not know what you're talking about. SerialVersionUID numbers are meaningless. They are cryptographic functions of the class signature. They are not intended to be meaningful to anybody but the Serialization subsystem. If you're using them for some other purpose, you're breaking a cardinal rule of computing - a field should not be used for more than one purpose. Don't.
    In any case the solution I gave is by a long chalk the most practical.
    Is it possible to de-serialise an object, change its
    serialVersionUID and then save it again.Why on earth would you go to all this useless bother when you already have a solution?

  • Deserializing a file not serialized using Java

    Hello ,
    I am trying to deserialize and read a file which has been previously serialized using VC++. Is there a way to read a file serialized by VC++ using Java. When i read using ObjectInputStream, exception is thrown (StreamCorruptedException). The file structure of the serialized file is as below:
    PC Records(Array)
    ObjectRecord
    Name;(string)
    SecurityLevel;(unsigned char)
    SecurityGroup;(string)
    ScanTime;(unsigned char)
    ElementNum;(int)
    PCDevice;(unsigned char)
    m_SerNum[5];(unsigned char)
    m_DeviceChanCount; (unsigned char)
    m_ModelID; (unsigned char)
    m_ChanNum; (unsigned char)
    m_LastBlock; (unsigned short)
    m_ScanTime; (unsigned char)
    m_Owner; (unsigned char)
    m_Gain; (unsigned char)
    PCPath;(string)
    m_PCName;(string)
    a; (unsigned char)
    b; (unsigned char)
    could somebody help me deserialize and read this file using Java. Any help and sample source code is greatly appreciated.

    This can't be read from Java Serialization API 'cause Java Serialization API has it's on propietary format (that's one reazon why J2SE 1.4 introduced XML serialization)
    If you need to read a file serialized in VC++, you will need to implement the code to read the file in Java.
    If you only need to read the file secuentially (one record after the other loaded into memory) you can use a java.io.FileInputStream, and wrap it in a java.io.BufferInputStream to optimize reading.
    The interface java.io.DataInput have a lot of methods you can use to read the fields (read signed ints, unsigned ints, chars, bytes). You can use then java.io.DataInputStream to wrap InputStream and read this kind of fields. You have to take special care with chars and strings, 'cause they are unicode in java and probably only ASCII on the VC++ generated file. Probably strings will have to be read byte after byte until the \0 mark is reached, unless string fields have a predefined length, in this case you can read [length] bytes from the input stream and create a string from this array.
    If you need random access then you need java.io.RandomAccessFile, it also implements java.io.DataInput, so you have the methods to read ints, shorts, bytes, etc.
    UTF strings are strings using UTF encoding, so probably this method will not help much in this case.
    Rivas

  • How can Java read VC++ serialized achieve file

    After finally realizing Java is much more powerful than C++, I am currently transferring my VC++ codes to Java and having a problem on how to read my old VC++ serialized achieve files. In java.io, can readObject() do the same job as VC++'s Serialize(ar)?
    In VC++ codes, my data was structured as the following:
    struct TickData {
         time_t     time;
         double     price;
         int     size;
    CList<TickData, TickData &> m_tickList[TICKER_MAX];
    m_tickList[nId].Serialize(ar); // VC++ data was saved this way
    Does anyone know what java method and how I should use to read all my old VC++ serialized files?
    Help on this will be greatly appreciated! Thanks.

    Unless you find some library somwhere, I strongly suggest to write a conversion tool in VC++.
    It takes a serialized file as input and spits out a file in a language independent format: XML,
    CSV, INI, Java properties, whatever. You Java program will use this format, not serialization,
    so you will never have this kind of problems in the future.

  • Reading a Random Line from a Text File

    Hello,
    I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
    Here is my code, and the text file that the program reads from is called 'wordFile'
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class WordColor extends JFrame{
         public WordColor(){
              super("WordColor");
              setSize(1000,500);
              setVisible(true);
              add(new WordPanel());
         public static void main(String[]r){
              JFrame f = new WordColor();
    class WordPanel extends JPanel implements KeyListener{
         private Graphics2D pane;
         private Image img;
         private char[]characterList;
         private CharacterPosition[]positions;
         private int charcounter = 0;
         private String initialWord;
         private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
         private FontMetrics fm;
         private javax.swing.Timer timer;
         public final static int START = 20;
         public final static int delay = 10;
         public final static int BOTTOMLINE = 375;
         public final static int buffer = 15;
         public final static int distance = 4;
         public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
                                                                          Color.magenta,Color.orange,Color.pink};
         public static String[] words;
         public static int descent;
         public static int YAXIS = 75;
         public static int SIZE = 72;
         public WordPanel(){
              words = readWords();
              setLayout(new BorderLayout());
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              setFocusable(true);
              addKeyListener(this);
              timer = new javax.swing.Timer(delay,new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        YAXIS += 1;
                        drawWords();
                        if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
                        if (allColorsOn()) win();
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              if (img == null){
                   img = createImage(getWidth(),getHeight());
                   pane = (Graphics2D)img.getGraphics();
                   pane.setColor(Color.white);
                   pane.fillRect(0,0,getWidth(),getHeight());
                   pane.setFont(new Font("Arial",Font.BOLD,SIZE));
                   pane.setColor(Color.black);
                   drawThickLine(pane,getWidth(),5);
                   fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
                   descent = fm.getDescent();
                   distributePositions();
                   drawWords();
                   timer.start();
              g.drawImage(img,0,0,this);
         private void distributePositions(){
              int xaxis = START;
              positions = new CharacterPosition[characterList.length];
              int counter = 0;
              for (char c: characterList){
                   CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
                   positions[counter] = cp;
                   counter++;
                   xaxis += fm.charWidth(c)+distance;
         private void drawThickLine(Graphics2D pane, int width, int thickness){
              pane.setColor(Color.black);
              for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
                   pane.drawLine(0,j,width,j);
         private void drawWords(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              drawThickLine(pane,getWidth(),5);
              for (CharacterPosition cp: positions){
                   int x = cp.getX();
                   char print = cp.getChar();
                   pane.setColor(cp.getColor());
                   pane.drawString(""+print,x,YAXIS);
              repaint();
         private boolean allColorsOn(){
              for (CharacterPosition cp: positions){
                   if (cp.getColor() == Color.black) return false;
              return true;
         private Color randomColor(){
              int rand = (int)(Math.random()*colors.length);
              return colors[rand];
         private void restart(){
              charcounter = 0;
              for (CharacterPosition cp: positions){
                   cp.setColor(Color.black);
         private void win(){
              timer.stop();
              newWord();
         private void newWord(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              repaint();
              drawThickLine(pane,getWidth(),5);
              YAXIS = 75;
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              distributePositions();
              charcounter = 0;
              drawWords();
              timer.start();
         private void lose(){
              timer.stop();
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              pane.setColor(Color.red);
              pane.drawString("Sorry, You Lose!",50,150);
              repaint();
              removeKeyListener(this);
              final JPanel p1 = new JPanel();
              JButton again = new JButton("Play Again?");
              p1.add(again);
              add(p1,"South");
              p1.setBackground(Color.white);
              validate();
              again.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        remove(p1);
                        addKeyListener(WordPanel.this);
                        newWord();
         private String getWord(){
              int rand = (int)(Math.random()*words.length);
              return words[rand];
         private String[] readWords(){
              ArrayList<String> arr = new ArrayList<String>();
              try{
                   BufferedReader buff = new BufferedReader(new FileReader(wordFile));
                   try{
                        String line = null;
                        while (( line = buff.readLine()) != null){
                             line = line.toUpperCase();
                             arr.add(line);
                   finally{
                        buff.close();
              catch(Exception e){e.printStackTrace();}
              Object[] objects = arr.toArray();
              String[] words = new String[objects.length];
              int count = 0;
              for (Object o: objects){
                   words[count] = (String)o;
                   count++;
              return words;
         public void keyPressed(KeyEvent evt){
              char tempchar = evt.getKeyChar();
              String character = ""+tempchar;
              if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
                   positions[charcounter].setColor(randomColor());
                   charcounter++;
              else if (evt.isShiftDown()){
                   evt.consume();
              else{
                   restart();
              drawWords();
         public void keyTyped(KeyEvent evt){}
         public void keyReleased(KeyEvent evt){}
    class CharacterPosition{
         private int xaxis;
         private char character;
         private Color color;
         public CharacterPosition(char c, int x, Color col){
              xaxis = x;
              character = c;
              color = col;
         public int getX(){
              return xaxis;
         public char getChar(){
              return character;
         public Color getColor(){
              return color;
         public void setColor(Color c){
              color = c;
    }

    I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
    class WordList extends ArrayList<String>{
      long updated;
    WordList readWordList(File file) throws Exception{
      WordList list = new WordList();
      BufferedReader in = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = in.readLine()) != null){
        list.add(line);
      in.close();
      list.updated = file.lastModified();
      return list;
    WordList wordList;
    File datFile = new File("words.dat");
    File txtFile = new File("input.txt");
    if (datFile.exists()){
      ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
      wordList = (WordList)input.readObject();
      if (wordList.updated < txtFile.lastModified()){
        //if the text file has been updated, re-read it
        wordList = readWordList(txtFile);
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
        output.writeObject(wordList);
        output.close();
    } else {
      //serialized list does not exist--create it
      wordList = readWordList(txtFile);
      ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
      output.writeObject(wordList);
      output.close();
    }The text file contained one random sequence of letters per line. For example:
    hwnuu
    nhpgaucah
    zfbylzt
    hwnc
    gicgwkhStats:
    Text file size: 892K
    Serialized file size: 1.1MB
    Time to read from text file: 795ms
    Time to read from serialized file: 1216ms

  • Appending Objects to a File using serialization

    hi,
    I was wondering if I can append objects in a single file. For example, suppose there are 2 .java files. 1st file creates the Serialized file caleed sl.dat, opens it, writes the object, close it down.
    The 2nd file nw open that same file, sl.dat, in append mode, writes one more object and close it down.
    next I want to read each object of the file. Will it work in this fashion?
    I found a quite interesting discussion here. but it says that it is not possible.. is that true?
    Any clue? Is there any other mean to achieve this?

    arin wrote:
    kajbj wrote:
    I've done it by subclassing ObjectOutputStream. I could then add a constructor that took an argument that indicated if a header should be written or not.Can you explain what I need to done here... I have a class which extends ObjectOutputStream but what to do after that? What do u mean by header in the constructor?? Please help meYou do know that you have the source code for the class if you have a JDK? The source for ObjectOutputStream is in the src.zip.
    The normal constructor calls writeStreamHeader, and that is the problem if you are going to append data since you don't want to get the stream header more than once. Create a constructor that takes a boolean as argument, and only calls writeStreamHeader if the boolean is true.
    Kaj

Maybe you are looking for

  • Acrobat 9 and Canon iR-ADV C2030 issues

    I have a user running 10.7.5 on a 2ghz MacBook Pro who constantly has issues printing PDFs to various printers.  When she prints tabloid PDFs to our copier (Canon iR-ADV C2030), the prints come out fine.  When she prints tabloid PDFs to any of our ot

  • Please help....what to g

    for some reason there is only player on the market that records AM radio. i just found out that the n200 can record from any audio source. i have a vew small am/fm radio that i would just hook upto the n200. i want to get it but i have a few question

  • IWork apps cannot be opened in Lion.

    Moving to a new MacBook Pro with 10.7.3 and iWork 09 apps "cannot be opened because of a problem".Trying to update iWork and keep getting message: "Alert - A newer version of Keynote is already installed" even after reinstalling iWork from the disk.

  • Terminal doesn't show changes immediately

    Hi, since some days I have an annoying problem: When I type something, for example 10 x [Return], my xterm doesn't "react" immediately. Nothing happens for at least several seconds. When I switch the window and switch back the input / command is show

  • Mac won't start after downloading Mountain Lion

    Downloaded Mountain Lion today ,when I restarted my IMac it won't reboot . Screen shows a circle with a line through it . Please help