File I/O Using Object Streams

My program is supposed to be a Driving instructor program that allows someone to enter a Name and Lesson Number, and it will pull up the Date, and Comments that the lesson took place. The information is saved in a file with the person's name, and saved as an array. We are required to use Object Streams for the file i/o. The only part of the program that I don't have working is the actual file i/o. The large commented section that I have in the datamanager class is the notes from the professor on the board and I haven't removed them yet. There are 4 classes for this file.
The main class that creates the program and calls the other classes.
import java.awt.*;
import javax.swing.*;
public class main {
/** Creates a new instance of main */
public main() {
* @param args the command line arguments
public static void main(String[] args)
guiLayout labelFrame = new guiLayout(); // creates LabelFrame
labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
labelFrame.setSize(600, 200);
labelFrame.setVisible(true);
} The second class is the GUI class and event handler class.
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class guiLayout extends JFrame{
    private JPanel centertop;
    private JPanel centermiddle;
    private JPanel centerbottom;
    private JLabel dateLabel;
    private JLabel nameLabel;
    private JLabel lessonLabel;
    private JLabel commentsLabel;
    private JTextArea DateTextArea;
    private JTextArea NameTextArea;
    private JTextArea LessonTextArea;
    private JTextArea CommentsTextArea;
    private JButton Save;
    private JButton Retrieve;
    private String tempDay[];
    private DataManager DMO;
    /** Creates a new instance of guiLayout */
    public guiLayout()
        super("Drive Application");
        setLayout(new FlowLayout());
        dateLabel = new JLabel("Date (mm/dd/yy)");
        nameLabel = new JLabel("Name");
        lessonLabel = new JLabel("Lesson (1-10)");
        commentsLabel = new JLabel("Comments");
        DateTextArea = new JTextArea(1, 7);
        NameTextArea = new JTextArea(1, 15);
        LessonTextArea = new JTextArea(1, 2);
        CommentsTextArea = new JTextArea(6, 30);
        Save = new JButton( "Save");
        Retrieve = new JButton( "Retrieve");
        //insert into GUI
        //TOP
        centertop = new JPanel();
        centertop.add(nameLabel);
        centertop.add(NameTextArea);
        centertop.add(lessonLabel);
        centertop.add(LessonTextArea);
        centertop.add(dateLabel);
        centertop.add(DateTextArea);
        centertop.setLayout(new GridLayout(6,1));
        add(centertop, BorderLayout.NORTH);
        centermiddle = new JPanel();
        centermiddle.setLayout(new GridLayout(1,1));
        centermiddle.add(CommentsTextArea);
        add(centermiddle, BorderLayout.CENTER);
        centerbottom = new JPanel();
        centerbottom.setLayout(new GridLayout(1,3));
        centerbottom.add (Save);
        centerbottom.add(Retrieve);
        add(centerbottom, BorderLayout.SOUTH);
        ButtonHandler handler = new ButtonHandler();
        Save.addActionListener( handler);
        Retrieve.addActionListener(handler);
    private class ButtonHandler implements ActionListener
        public void actionPerformed(ActionEvent event)
            String Namein = NameTextArea.getText();
            String Datein = DateTextArea.getText();
            String Commentsin = CommentsTextArea.getText();
            int Lessonin = Integer.parseInt(LessonTextArea.getText());
            if(event.getSource()==Save)
               DMO.Save(Namein, Datein, Commentsin, Lessonin);
            if(event.getSource()==Retrieve)
                if(Lessonin >= 1 && Lessonin <= 10)
                   LessonRecord r = (DMO.Retrieve(Namein, Lessonin));
                else
                    String errormess = "Lesson Number must be between 1 and 10!";
                    CommentsTextArea.setText(errormess);
}The third class is the DataManager class which handles the actual file i/o.
import java.io.*;
import java.util.*;
public class DataManager implements Serializable
    //private String Path = "P:\\D00766703\\CET431\\Assign5";
    private String Path = "C:\\Java";
    FileInputStream fin;
    FileOutputStream fout;
    ObjectInputStream oin;
    ObjectOutputStream oout;
    public String Retrieve(String name, int lesson)
        String itemFile = Path + name + ".ser";
        File f = new File(itemFile);
        if (f.exists() == true)
            try
                if(fin == null)
                    fin = new FileInputStream(itemFile);
                    oin = new ObjectInputStream(fin);
                LessonRecord r[] = oin.readObject();
                if(fin.available() == 0)
                    oout.close();
                    fout.close();
                    return r[lesson - 1];
            catch(IOException ioe)
                System.out.print(ioe);
        else
            LessonRecord LR = new LessonRecord();
            LR.date = " ";
            LR.comment = "File Not Found";
            return LR;
    /*create file object for Path\\Name
     *if file exists
     *  create fileinputstream
     *  create objectinputstream - oin
     *  read array of lesson records
     *  LessonRecord |r[] = oin.readObject();    need cast to array here
     *  close object input stream and file input stream
     *  return |r[lesson - 1];
     *else file does NOT EXIST
     *  LessonRecord LR = new LessonRecord();
     *  LR.date = " ";
     *  LR.comment = error message;
     *  return LR;
    public void Save(String name, String date, String comment, int lesson)
        String itemFile = Path + name + ".ser";
        File f = new File(itemFile);
        LessonRecord |r[];
        if (f.exists() == true)
            try
                fin = new FileInputStream(itemFile);
                oin = new ObjectInputStream(fin);
                LessonRecord r[] = oin.readObject();
            catch(IOException ioe)
                System.out.print(ioe);
        else
            r = new LessonRecord[10];
        r[lesson - 1] = new LessonRecord(date, comment);
        fout = new FileOutputStream(itemFile, true);
        oout = new ObjectOutputStream(fout);
        oout.write(r);
        oout.close();
        fout.close();
    /*create file object for Path\\Name
     *LessonRecord |r[];
     *if file exists
     *  create fileinputstream
     *  create objectinputstream - oin
     *  read array of lesson records
     *  LessonRecord |r[] = oin.readObject();    need cast to array here
     *  close object input stream and file input stream
     *else
     *  |r = new LessonRecord[10];
     *|r[lesson - 1] = new LessonRecord(date, comment);
     *createfileoutputstream(BaseDir\\Name);
     *createobjectoutputstream - oout
     *oout.write(|r);
     *closeobjectstream
     *closefilestream
}And the fourth class is the LessonRecord class which is serializable and has the date and comments variables.
import java.io.Serializable;
public class LessonRecord implements Serializable
    public String Date;
    public String Comment;
    /** Creates a new instance of LessonRecord */
    public LessonRecord()
        Date = "";
        Comment = "";
    public LessonRecord(String Datein, String Commentin)
        Date = Datein;
        Comment = Commentin;
}I could have sworn that the professor said to make it |r for the account records variable names, but I always get errors when I do that, and I need to know how to cast to an array too.

hi Friend,
I have made some modification to your code. and try this...I think it will help you...
/*guiLayout.java*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class guiLayout extends JFrame{
    private JPanel centertop;
    private JPanel centermiddle;
    private JPanel centerbottom;
    private JLabel dateLabel;
    private JLabel nameLabel;
    private JLabel lessonLabel;
    private JLabel commentsLabel;
    private JTextArea DateTextArea;
    private JTextArea NameTextArea;
    private JTextArea LessonTextArea;
    private JTextArea CommentsTextArea;
    private JButton Save;
    private JButton Retrieve;
    private String tempDay[];
    private DataManager DMO;
    /** Creates a new instance of guiLayout */
    public guiLayout()
        super("Drive Application");
        DMO=new DataManager();
        setLayout(new FlowLayout());
        dateLabel = new JLabel("Date (mm/dd/yy)");
        nameLabel = new JLabel("Name");
        lessonLabel = new JLabel("Lesson (1-10)");
        commentsLabel = new JLabel("Comments");
        DateTextArea = new JTextArea(1, 7);
        NameTextArea = new JTextArea(1, 15);
        LessonTextArea = new JTextArea(1, 2);
        CommentsTextArea = new JTextArea(6, 30);
        Save = new JButton( "Save");
        Retrieve = new JButton( "Retrieve");
        //insert into GUI
        //TOP
        centertop = new JPanel();
        centertop.add(nameLabel);
        centertop.add(NameTextArea);
        centertop.add(lessonLabel);
        centertop.add(LessonTextArea);
        centertop.add(dateLabel);
        centertop.add(DateTextArea);
        centertop.setLayout(new GridLayout(6,1));
        add(centertop, BorderLayout.NORTH);
        centermiddle = new JPanel();
        centermiddle.setLayout(new GridLayout(1,1));
        centermiddle.add(CommentsTextArea);
        add(centermiddle, BorderLayout.CENTER);
        centerbottom = new JPanel();
        centerbottom.setLayout(new GridLayout(1,3));
        centerbottom.add (Save);
        centerbottom.add(Retrieve);
        add(centerbottom, BorderLayout.SOUTH);
        ButtonHandler handler = new ButtonHandler();
        Save.addActionListener( handler);
        Retrieve.addActionListener(handler);
    private class ButtonHandler implements ActionListener
        public void actionPerformed(ActionEvent event)
            String Namein = NameTextArea.getText();
            int Lessonin = Integer.parseInt(LessonTextArea.getText());
            if(event.getSource()==Save)
                String Datein = DateTextArea.getText();
                 String Commentsin = CommentsTextArea.getText();
               DMO.Save(Namein, Datein, Commentsin, Lessonin);
            if(event.getSource()==Retrieve)
                if(Lessonin >= 1 && Lessonin <= 10)
                   LessonRecord r = (DMO.Retrieve(Namein, Lessonin));
                   System.out.println("Retrieve:"+ r.Comment+":"+r.Date);
                else
                    String errormess = "Lesson Number must be between 1 and 10!";
                    CommentsTextArea.setText(errormess);
/*DataManager.java*/
import java.io.*;
import java.util.*;
public class DataManager implements Serializable
    //private String Path = "P:\\D00766703\\CET431\\Assign5";
    private String Path = "C:/Java";
    FileInputStream fin;
    FileOutputStream fout;
    ObjectInputStream oin;
    ObjectOutputStream oout;
    public LessonRecord Retrieve(String name, int lesson)
        String itemFile = Path + name + ".ser";
        File f = new File(itemFile);
        LessonRecord[] r=null;
        if (f.exists() == true)
            try
                if(fin == null)
                    fin = new FileInputStream(itemFile);
                    oin = new ObjectInputStream(fin);
                r= (LessonRecord[])oin.readObject();
                System.out.println(r[lesson-1].Comment+":"+r[lesson-1].Date);
            catch(IOException ioe)
                System.out.print(ioe);
              catch(ClassNotFoundException c){
                c.printStackTrace();
            finally
                try {
                    if(fin!=null)fin.close();
                    if(oin!=null)oin.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
        else
            LessonRecord LR = new LessonRecord();
            LR.Date = " ";
            LR.Comment = "File Not Found";
            return LR;
    /*create file object for Path\\Name
     *if file exists
     *  create fileinputstream
     *  create objectinputstream - oin
     *  read array of lesson records
     *  LessonRecord |r[] = oin.readObject();    need cast to array here
     *  close object input stream and file input stream
     *  return |r[lesson - 1];
     *else file does NOT EXIST
     *  LessonRecord LR = new LessonRecord();
     *  LR.date = " ";
     *  LR.comment = error message;
     *  return LR;
  return r[lesson - 1];
    public void Save(String name, String date, String comment, int lesson)
        String itemFile = Path + name + ".ser";
        File f = new File(itemFile);
        LessonRecord r[]=new LessonRecord[10];
        if (f.exists() == true)
            try
                fin = new FileInputStream(itemFile);
                oin = new ObjectInputStream(fin);
                 r = (LessonRecord[])oin.readObject();
            catch(IOException ioe)
                System.out.print(ioe);
            catch(ClassNotFoundException c){
                c.printStackTrace();
            finally
                try {
                    if(fin!=null)fin.close();
                    if(oin!=null)oin.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
        else
            r = new LessonRecord[10];
   try
        r[lesson - 1] = new LessonRecord(date, comment);
        fout = new FileOutputStream(itemFile);
        oout = new ObjectOutputStream(fout);
        oout.writeObject(r);
        oout.flush();
   catch(IOException ioe)
        finally
            try {
                if(fout!=null)fout.close();
                if(oout!=null)oout.close();
            } catch (IOException ex) {
                ex.printStackTrace();
    /*create file object for Path\\Name
     *LessonRecord |r[];
     *if file exists
     *  create fileinputstream
     *  create objectinputstream - oin
     *  read array of lesson records
     *  LessonRecord |r[] = oin.readObject();    need cast to array here
     *  close object input stream and file input stream
     *else
     *  |r = new LessonRecord[10];
     *|r[lesson - 1] = new LessonRecord(date, comment);
     *createfileoutputstream(BaseDir\\Name);
     *createobjectoutputstream - oout
     *oout.write(|r);
     *closeobjectstream
     *closefilestream
}main.java and LessonRecord.java does not have any changes so you use the old code....
Thanks
Edited by: rajaram on Sep 28, 2007 1:24 PM

Similar Messages

  • Random access file with object stream

    Hi All,
    I have saved some objects in a file using object stream. While reading the sequential read is possible for me. I want to reduce the overhead of reading whole file for getting one specific object details. Is there any way in which we can implement RandomAccessFile with object stream? or is there any other alternative of reaching specific object in the file without seqential read?

    is there any
    other alternative of reaching specific object in the
    file without seqential read?Write the objects to a database.

  • How to Edit/Save PDF without Object Stream Compression?

    Hi,
    Whenever I am removing/replacing a page in the PDF file, "Object Stream Compression" applied automatically. But in the original PDF there is no "Object Stream Compression" initially.
    I can remove this "Object Stream Compression" using the option "PDF OPTIMIZER->Cleanup->Remove->Compression" manually, but I want to remove/replace a page in the PDF file without "Page Has Object Stream Compression".
    Preflight Report for the Original PDF
    Preflight Report for the Edited PDF (One Page Removed)
    Could you advise anyone, how to solve the above mentioned issue?
    I hope your favorable response from the Acrobat experts.
    Regards,
    TSR

    Thanks for the reply.
    I just want to remind you that I don't use any other workflow to retain/remove the "object stream compression".
    My question is "object stream compression" was not present in the original PDF  but after removing a page (Ex: Back cover) "object stream compression" applied automatically. Why?
    Note: I am using "Acrobat X pro" to remove a page (Ex: Back cover) from the original PDF and not using any other PDF tools for the above.
    Now i hope that you will understand the actual issue.
    Regards,
    Raja. S

  • Socket + GZip Stream + Object Stream problem

    Hello,
    I've been having a problem with my threaded networked application. I want to send GZipped Objects over a socket, but the ObjectInputStream constructor blocks. I understand that it is waiting for header information from the corresponding ObjectOutputStream. I am sure that the socket connection has been established, and the ObjectOutputStream is constructed before the ObjectInputStream on the other end. The header information never seems to get to the other end.
    If I remove the Gzip filter stream, everything works great. I'm thinking that the Gzip stream is buffering the 4 bytes of header info, waiting for more data before actually compressing anything. I've tried flushing everything, to no help. I've tried finish()ing the Gzip stream, but that means I can't send my object payload. I've checked the buffers of all the stream objects and see the Object Stream's header in its buffer, but never seems to get into the GZIPOutputStream's buffer.
    Has anyone successfully used Object Stream > GZIP Stream > Socket Stream before?
    I'm not interested in examples that use file streams, since I get the impression that Gzip works fine with those (and maybe even designed only for those, not for sockets).
    Thanks for any help.
    Dave C

    Thanks. I see what I'm doing differently now. I was trying to send multiple objects over the gzip stream, not 1 at a time, finish(), and construct a new Gzip and Object output stream.
    Seems to work with a ByteArrayOutput/InputStream, now to try with a socket..

  • Root object in Object Stream in Encrypted file

    I cannot find anywhere in the PDF Spec a prohibition on including the Root object in an Object Stream in a non-linearized encrypted file, but Acrobat products appear to assume such a restriction.
    Encrypted files where the Root obj is in an Object Stream do not open with Acrobat 7, 8 or Reader 9, but do open with GhostView/Ghostscript, Foxit, and Adobe Digital Editions.
    If the file is not encrypted there is no problem with the Root object appearing in an Object Stream, and if the Root object is a 'normal' encrypted object there is also no problem.
    Anyone any ideas?
    Matthew Fitzgerald

    Hey praveen,
    If you dont use ehp1, there is no any transaction to create root object. you can fallow this [wiki|http://wiki.sdn.sap.com/wiki/display/CRM/CreateaZBOLObjectPart1] page.
    Regards,
    Zafer,

  • How to embed jnlp file into html page using object tag

    hi everyone,
    i have written one jnlp file like this.
    <?xml version="1.0" encoding="utf-8" ?>
    <!-- JNLP file for Demo applicaion -->
    <jnlp spec="1.0+" codebase="http://localhost:9080/base/" href="SampleExample.jnlp">
         <information>
              <title>Demo Application</title>
              <vendor> </vendor>
              <description>Sample Demo Application</description>
              <offline-allowed/>
         </information>
         <security/>
         <resources>
              <j2se version="1.3+" />
              <jar href="common.jar" main="true" download="eager" />
              <jar href="classes12.jar" download="eager" />
              <jar href="toplink.jar" download="eager"/>
              <package name="com.applet.*" part="applet" recursive="true"/>
         </resources>
         <applet-desc name="grid" main-class="com.applet.PriceGrid" width="1000" height="300"/>
    </jnlp>
    i am trying embed that jnlp file using object tag like
    <OBJECT
    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH="1000" HEIGHT="300" NAME="grid">     
    <PARAM NAME="jnlp" VALUE="http://localhost:9080/base/SampleExample.jnlp">
    </OBJECT>
    but i am not able to load the applet using Web Start.
    Can anyone please help me. This is very Urgent for me.
    Thanks & Regards,
    Shiva.

    thanks.
    i am giving my problem clearly. i have one applet. Previously i am loading the applet in my html page using object tag like this...
    <OBJECT
    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH="1000" HEIGHT="300" NAME="grid">
    <PARAM NAME="CODE" VALUE="com.adp.base.applet.PriceGrid.class" >
         <PARAM NAME="ARCHIVE" VALUE="common.jar,classes12.jar,toplink.jar" >
         <PARAM NAME="NAME" VALUE="grid" >
    <PARAM NAME="type" VALUE="application/x-java-applet">
    <PARAM NAME= "cache_option" VALUE ="no">
    </OBJECT>
    now what i need to do is
    i need load the applet only first time using web start and when ever the applet code changes in the server i need to reload the applet.
    for that i kept all the applet resources in .jnlp file.i want to cache all the resources which are in .jnlp file and applet must be displayed within a web page within a browser.
    Webstart always open a new application windows.
    I need to run an Applet embedded within a web page within a browser.
    Is there a way to still use Webstart?

  • Can't share photos using photo stream in iCloud. File is always blank.

    Can't share photos using photo stream in iCloud. File is always blank.

    Hello desert_dweller5,
    It sounds like you art trying to access a Shared Photo Stream, but you do not have one of the devices to enable your Apple ID as an iCloud account.  The following article provides information on how Shared Photo Streams work:
    iCloud: Photo Stream FAQ
    http://support.apple.com/kb/HT4486
    The article states that for privately Shared Photo Streams to work, the recipient will not only have to have an Apple ID, but it will have to be an iCloud account:
    Friends and family with iCloud accounts can view your photos in the Photos app on any device using iOS 6 or later; on a Mac in iPhoto 9.4 or Aperture 3.4 or later; on a Windows PC with Windows Vista or later and iCloud Control Panel 2.0 or later installed; or on a second generation or later Apple TV with software version 5.1 or later installed. They can also view your photos on the web if you enable Public Website in the settings or options for your Shared Photo Stream.
    Since you do not have an iCloud account and just and Apple ID, your friend can share the photo stream as a public website so that you can view it, as stated in the same article: 
    Can I share with people who don't have an iCloud account?
    Yes. If you enable Public Website in the settings or options for your shared photo stream your photos will be published to a website that anyone can view in an up-to-date web browser.
    To be able to change an Apple ID to an iCloud account, you would need an iPhone, iPad, or iPod touch with iOS 5 or later or a Mac with OS X Lion v10.7.4 or later as stated in the following article:
    Creating an iCloud account: Frequently Asked Questions
    http://support.apple.com/kb/HT4436
    Best,
    Sheila M.

  • How to compress non-image object streams using maximum compression in acrobat x pro

    How to compress non-image object streams using maximum compression in acrobat x pro
    Please provide the screenshot if possible. Thanks!

    ZIP is the best compression for non-image streams, and it will almost certainly already have been used.

  • [svn:osmf:] 13603: Use actual streaming audio file for streaming audio example.

    Revision: 13603
    Revision: 13603
    Author:   [email protected]
    Date:     2010-01-18 17:09:10 -0800 (Mon, 18 Jan 2010)
    Log Message:
    Use actual streaming audio file for streaming audio example.
    Modified Paths:
        osmf/trunk/apps/samples/framework/ExamplePlayer/org/osmf/examples/AllExamples.as

    It seems that you do not understand the problem at hand. I can listen on a m3u list using iTunes, VLC and other players, but I wish to listen on m3u lists as streaming music when I am on sites such as eMusic. For instance, I cannot listen on sample music at eMusic, but must download it first. Thus, it is not possible to listen on streaming music with Firefox. On the other hand, Opera and Safari handle m3u streaming music very well.
    Can you listen streaming music or samples at eMusic using Firefox without downloading m3u-list on your local disk?

  • To convert multiple image files to pdf using pdfsharp in C#

    Hey guys I have this C# code to convert any image file to .pdf using pdfsharp.dll. But I want to select multiple images for conversion please help. here's my code (plz note enable pdfsharp.dll in the reference)
    usingSystem;
    usingSystem.Collections.Generic;
    usingSystem.Linq;
    usingSystem.Text;
    usingSystem.Threading.Tasks;
    usingPdfSharp.Pdf;
    usingPdfSharp.Drawing;
    usingSystem.IO;
    namespaceConsoleApplication1
    classProgram
    staticvoidMain(string[]
    args)
    PdfDocumentdoc =
    newPdfDocument();
    doc.Pages.Add(newPdfPage());
    XGraphicsxgr =
    XGraphics.FromPdfPage(doc.Pages[0]);
    XImageimg =
    XImage.FromFile(source
    path...);
    xgr.DrawImage(img,0,0);
    doc.Save(destination path...);
    doc.Close();

    try this one
    public string CreatePDF(System.Collections.Generic.List<byte[]> images)
    dynamic PDFGeneratePath = Server.MapPath("../images/pdfimages/");
    dynamic FileName = "attachmentpdf-" + DateTime.Now.Ticks + ".pdf";
    if (images.Count >= 1) {
    Document document = new Document(PageSize.LETTER);
    try {
    // Create pdfimages directory in images folder.
    if ((!Directory.Exists(PDFGeneratePath))) {
    Directory.CreateDirectory(PDFGeneratePath);
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.GetInstance(document, new FileStream(PDFGeneratePath + FileName, FileMode.Create));
    // opens up the document
    document.Open();
    // Add metadata to the document. This information is visible when viewing the
    // Set images in table
    PdfPTable imageTable = new PdfPTable(2);
    imageTable.DefaultCell.Border = Rectangle.NO_BORDER;
    imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
    for (int ImageIndex = 0; ImageIndex <= images.Count - 1; ImageIndex++) {
    if ((images(ImageIndex) != null) && (images(ImageIndex).Length > 0)) {
    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(SRS.Utility.Utils.ByteArrayToImage(images(ImageIndex)), System.Drawing.Imaging.ImageFormat.Jpeg);
    // Setting image resolution
    if (pic.Height > pic.Width) {
    float percentage = 0f;
    percentage = 400 / pic.Height;
    pic.ScalePercent(percentage * 100);
    } else {
    float percentage = 0f;
    percentage = 240 / pic.Width;
    pic.ScalePercent(percentage * 100);
    pic.Border = iTextSharp.text.Rectangle.BOX;
    pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
    pic.BorderWidth = 3f;
    imageTable.AddCell(pic);
    if (((ImageIndex + 1) % 6 == 0)) {
    document.Add(imageTable);
    document.NewPage();
    imageTable = new PdfPTable(2);
    imageTable.DefaultCell.Border = Rectangle.NO_BORDER;
    imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
    if ((ImageIndex == (images.Count - 1))) {
    imageTable.AddCell(string.Empty);
    document.Add(imageTable);
    document.NewPage();
    } catch (Exception ex) {
    throw ex;
    } finally {
    // Close the document object
    // Clean up
    document.Close();
    document = null;
    return PDFGeneratePath + FileName;

  • How can you use multiple stream types with one socket?

    Hi,
    I'm working on a large program that currently uses Object Input/Output streams for all of the messaging in a client/server application. This works fine except when files need to be transferred. In many cases using a Object stream to send a file can be 30 times slower than using a Buffered input/output stream. I've found I can combined the two. Here are some code snippets to give you a basic idea of what's happening...
    BufferedInputStream bis = new BufferedInputStream( serverSocket.getInputStream( ) );
    ObjectInputStream ois = new ObjectInputStream( serverSocket.getInputStream( ) );
    //this code runs on a thread on the server
    while( true ){
    switch( whichKindOfStreamUsedNext ){
    case OBJECT_STREAM:
    Object object = ois.readObject( );
    doSomethingWithObject( object );
    break;
    case BUFFERED_STREAM:
    readFromBuffer( bis );
    break;
    Obviously there is a lot missing here. Basically the variable whichKindOfStreamUsedNext is changed in the methods doSomethingWithObject( ) and readFromBuffer depending on what the current state of the server is and what is passed to these methods from the client.
    Here is the problem. If readFromBuffer( ) does a very small task and the client sends an object through an object stream everything is okay. I've switched whichKindOfStreamUsedNext = OBJECT_STREAM before that point and by the time the client sends the object the server is waiting on Object object = ois.readObject( );. However if the method readFromBuffer( ) does a very time intensive task and it takes a while to return and meanwhile the client sends an object then the server never gets that object. Does anyone have an easy solution to this problem. (Changing the whole program to just using BufferedStreams is not a solution).
    Thanks.

    Thanks a lot for the response.
    I guess I didn't realize I could do that.
    I changed how I am doing the program anyways. Sending flags to switch streams was a little messy. but now I have a new problem. I've discovered that mixing object streams with buffered streams also leads to significant speed increases. I do that in this manner...
    int ONE_MEG = 1024*1024;
    ObjectInputStream ois = new ObjectInputStream( new BufferedInputStream( socket.getInputStream( ), ONE_MEG ) );
    and I do the same thing for the ObjectOutputStream. It works very well when I just set up the client's output stream and the servers input stream in this manner. Upload times are increased from 60 seconds to 2-5 seconds.
    Unfortunately when I try to do the same thing with the servers output stream and the clients input stream to speed up downloads I get deadlock! As soon as the socket connection is opened and I try to set up the streams in this manner I get deadlock. Does anyone have any idea why this occurs and what I can do to fix it?

  • JSP XML file parsing XSLT using Xalan

    Hi all
    I have created an XML file "view_campaign.xml" using JSP as shown in a code below and i wanna know how i should proceed to parse the XML file and so i can display this XML as the XSLT file i created.
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    // Identify a carriage return character for each output line
    int iLf = 10;
    char cLf = (char)iLf;
    // Create a new empty binary file, which will content XML output
    File outputFile = new File("C:\\WebContent\\view_campaigns.xml");
    //outputFile.createNewFile();
    FileWriter outfile = new FileWriter(outputFile);
    // the header for XML file
    outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
    try {
         // Define connection string and make a connection to database
         //DriverManager.registerDriver (new org.apache.derby.jdbc.ClientDriver());
         Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/sample","app","app");
         Statement stat = conn.createStatement();
         // Create a recordset
         ResultSet rset = stat.executeQuery("Select * From campagn");
         // Expecting at least one record
         if( !rset.next() ) {
              throw new IllegalArgumentException("No data found for the campaigns table");
         outfile.write("<campaigns>"+cLf);
         outfile.write("<campaign>"+cLf);
         outfile.write("<campaign_id>" + rset.getString("campagn_id") +"</campaign_id>"+cLf);
         outfile.write("<campaign_name>" + rset.getString("campagn_name") +"</campaign_name>"+cLf);
         outfile.write("<campaign_type>" + rset.getString("campagn_type") +"</campaign_type>"+cLf);
         outfile.write("<client>" + rset.getString("client_name") +"</client>"+cLf);
         outfile.write("<positions>" + rset.getString("positions_nbr") +"</positions>"+cLf);
         outfile.write("<begin>" + rset.getString("campagn_beginning_date") +"</begin>"+cLf);
         outfile.write("<close>" + rset.getString("campagn_ending_date") +"</close>"+cLf);
         outfile.write("</campaign>"+cLf);
         // Parse our recordset
    // Parse our recordset
         while(rset.next()) {
              outfile.write("<campaign>"+cLf);
              outfile.write("<campaign_id>" + rset.getString("campagn_id") +"</campaign_id>"+cLf);
              outfile.write("<campaign_name>" + rset.getString("campagn_name") +"</campaign_name>"+cLf);
              outfile.write("<campaign_type>" + rset.getString("campagn_type") +"</campaign_type>"+cLf);
              outfile.write("<client>" + rset.getString("client_name") +"</client>"+cLf);
              outfile.write("<positions>" + rset.getString("positions_nbr") +"</positions>"+cLf);
              outfile.write("<begin>" + rset.getString("campagn_beginning_date") +"</begin>"+cLf);
              outfile.write("<close>" + rset.getString("campagn_ending_date") +"</close>"+cLf);
              outfile.write("</campaign>"+cLf);
         outfile.write("</campaigns>"+cLf);
         // Everything must be closed
         rset.close();
         stat.close();
         conn.close();
         outfile.close();
    catch( Exception er ) {
    %>////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    this is my .XSL file
    <?xml version="1.0" encoding="iso-8859-1" ?>
    - <!--  DWXMLSource="view_campaigns.xml"
      -->
      <!DOCTYPE xsl:stylesheet (View Source for full doctype...)>
    - <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="html" encoding="iso-8859-1" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
    - <xsl:template match="/">
    - <html xmlns="http://www.w3.org/1999/xhtml">
    - <head>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
      <title>Gestion des campagnes</title>
      </head>
    - <body>
      Gestion des campagnes
    - <table border="1">
    - <tr bgcolor="#9acd32">
      <th align="left">Code</th>
      <th align="left">Nom</th>
      <th align="left">Type</th>
      <th align="left">Client</th>
      <th align="left">Nombre de positions</th>
      <th align="left">Date d'ouverture</th>
      <th align="left">Date de cl�ture</th>
      </tr>
    - <xsl:for-each select="campaigns/campaign">
    - <tr>
    - <td>
      <xsl:value-of select="campaign_id" />
      </td>
    - <td>
      <xsl:value-of select="campaign_name" />
      </td>
    - <td>
      <xsl:value-of select="campaign_type" />
      </td>
    - <td>
      <xsl:value-of select="client" />
      </td>
    - <td>
      <xsl:value-of select="positions" />
      </td>
    - <td>
      <xsl:value-of select="begin" />
      </td>
    - <td>
      <xsl:value-of select="close" />
      </td>
      </tr>
      </xsl:for-each>
      </table>
      </body>
      </html>
      </xsl:template>
      </xsl:stylesheet>I would be greatful that u answer my question what i should do have any exemple case study.

    Hi,
    Try this code
    JspWriter out = pageContext.getOut(); // Get JSP output writter
          javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance(); //Instantiate a TransformerFactory.           
          String realPath = "c:/applyXsl.xsl";
          java.io.File file = new java.io.File(realPath); // crearte a file object for given XSL.
          // Use the TransformerFactory to process the stylesheet Source and  generate a Transformer.           
          javax.xml.transform.Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(file));
          java.io.StringReader inputStream = new java.io.StringReader("c:/xmlFile.xml"); // create an input stream for given XML doc
          java.io.ByteArrayOutputStream obj = new java.io.ByteArrayOutputStream(); // Create an output stream for XSL applied XML doc.
          // 3. Use the Transformer to transform an XML Source and send the output to a Result object.
          transformer.transform(new javax.xml.transform.stream.StreamSource(inputStream), new javax.xml.transform.stream.StreamResult(obj));
          String outputString = obj.toString(); // get the XSL applied applied XML document for print
          out.println(outputString); // print the XSL applied XML in to JSP.
    however you need xercesImpl.jar  and xml-apis.jar files  to run this program.
    Regards,
    Ananth.P

  • System code 1, error 43. English text was "Expected an object Stream"

    All,
    I have been working on the same form for several weeks (In Livecycle 8.0). Today when I went to open it, I get the error message "Library returned system code 1, error 43. English text was "Expected an object Stream" " and the only option I have is to say okay, and the windows closes.
    Background:
    The Original Form was a MS Word Document that I converted to a pdf, and use Livecycle 8.0 to add drop down menus, fields etc. to it.
    We have been using the form in reader for days, (testing it) and it still works fine in adobe reader, we can still open it without any problems.
    However I needed to add more options to my drop down menu's and when I attempt to open the pdf file in Livecycle, all of sudden I get this error, system code 1, error 43.
    I have googled, it a didnt find any help, and I have looked / searched the knowledge base with no luck.
    Thank you for any assistance!
    duffie

    I have not seen that error ...can you email it to [email protected] and I will have a look

  • Error with Object stream

    Hi ,
    I have to transfer a file using socket.
    Iam using java.util.zip to zip file the file to be transfered..
    At client,
    Iam getting the ZipOutputStream from the file to be transfered and wrtiing it to the SocketOutputStream
    At Server,
    Iam getting the ZipInputStream and extracting the zip file to get the original file.
    This is working fine.
    At the end of sending the zip file iam sending an object to acknowledge the server that data is transfered completely.
    At Client,
    iam getting the OutputStream from the socket and iam creating an ObjectOutputStream from that. Iam writing the Object to be transfered.
    At Server,
    Iam getting and inputStream from the socket. and when creating an objectInputStream over it iam getting the Invalid Stream Header Exception.
    Programs are as follows . . . .
    TestClient.java
    public class TestClient {
    public static void main ( String args[]) throws Exception {
    if (args.length < 2) {
    throw new Exception ("First arg is to be IP Addr." + "\n" +
    "and then the files to repliacte with path separated by blankspaces");
    String ip = new String();
    ip = args[0];
    String [] filenames = new String [(args.length - 1)];
    for (int i = 1; i < args.length; i ++) {
    filenames[i-1] = args;
    Socket s = new Socket();
    s = new Socket(ip, 4678);
    try {
    byte[] buf = new byte[1024*1024];
    OutputStream os = s.getOutputStream();
    ObjectOutputStream oos = null;
    ZipOutputStream out = new ZipOutputStream(os);
    for (int i=0; i<filenames.length; i++) {
    File f = new File(filenames[i]);
    FileInputStream in = new FileInputStream(f);
    ZipEntry ze = new ZipEntry(filenames[i]);
    ze.setSize(f.length());
    Date d = new Date(f.lastModified());
    System.out.println(d);
    ze.setTime(f.lastModified());
    out.putNextEntry(ze);
    System.out.println("Finished Writing zipEntry: " + ze +
    " with size: " + ze.getSize());
    int len;
    if (in.available() == 0) {
    System.out.println("No data is available in the " +
    "FileInputStream");
    continue;
    while ((len = in.read(buf)) > 0) {
    // System.out.println("Writing " + len +
    // "bytes of data into stream");
    out.write(buf, 0, len);
    in.close();
    out.closeEntry();
    out.finish();
    oos = new ObjectInputStream(s.getOutputStream());
    obj = new String("zipping");
    oos.writeObject(obj);
    } catch (IOException e) {
    e.printStackTrace();
    TestServer.java
    public class TestServer {
    public static void main ( String a[]) throws Exception {
    ServerSocket server = new ServerSocket(4678);
    while ( true ) {
    try {
    System.out.println( " Waiting for client ..." );
    Socket socket = server.accept();
    System.out.println( " Socket :: --> " + socket );
    InputStream is = socket.getInputStream();
    if (is == null ) {
    System.out.println("Socket Input Stream is null. Skipping");
    continue;
    while (is.available() <= 0 ) {
    System.out.println("No data vailable in Socket Input Stream");
    ObjectInputStream ois = null;
    ZipInputStream zis = new ZipInputStream(is);
    int len;
    System.out.println("conn status :: " + socket.isConnected());
    System.out.println("Reading from Zip Stream");
    try {
    byte[] buf = new byte[1024*1024];
    // while (zis.available() != 0) {
    ZipEntry ze = zis.getNextEntry();
    if (ze == null) {
    System.out.println("zipEntry is null. Exiting loop");
    break;
    System.out.println("Got a zipEntry: " + ze);
    long lastModified = ze.getTime();
    File fname = new File(ze.getName());
    DataOutputStream dos =
    new DataOutputStream(new FileOutputStream(fname));
    while (zis.available() <= 0 ) {
    System.out.println(
    "No data vailable in Zip Input Stream. Waiting...");
    long size = 2731;
    System.out.println("Going to read " + size + " bytes...");
    if((len = zis.read(buf)) >= 0) {
    System.out.println("Read data len: " + len);
    dos.write(buf,0,len);
    System.out.println("Done reading zipped data");
    zis.closeEntry();
    dos.close();
    fname.setLastModified(lastModified);
    ois = new ObjectInputStream(socket.getInputStream(socket.getInputStream());
    if (ois == null) {
    System.out.println("Object inputStream is null");
    while ((ois.available()) <= 0) {
    System.out.println("Nothing is there in object outputStream");
    System.out.println("available in object inputStream is " + ois.available());
    obj = ois.readObject();
    System.out.println("Object read is " + obj);
    } catch (Exception e) {
    System.out.println("couldn't read completely");
    e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    Iam getting the exception
    java.io.StreamCorruptedException: invalid stream header
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:737)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:253)
    at TestServer.main(TestServer.java:91)
    How to fix this exception
    With Regards
    Vara Prasad

    you're right da.futt. This is what I'm trying to get at. I wrote a program that has the zips and the objects matched up properly.
    package mypackage;
    import java.io.*;
    import java.util.zip.*;
    public class ziptest {
        static class MyBean implements Serializable {
            String beanName = "test";
        public static void main(String[] args) throws Exception {
            MyBean myBean = new MyBean();
            FileOutputStream fos = new FileOutputStream("mybean.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);
            zos.putNextEntry(new ZipEntry("myBean.ser"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            oos.writeObject( myBean );
            oos.close();
            FileInputStream fis = new FileInputStream("mybean.zip");
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry zipEntry = null;
            while( (zipEntry = zis.getNextEntry()) != null ) {
                System.out.println("processing file'" + zipEntry.getName() +
               ObjectInputStream ois = new ObjectInputStream(zis);
               MyBean m = (MyBean)ois.readObject();
                System.out.println("file contains property '" +
                    m.beanName + "'");
            zis.close();
    }

  • Create HelpSet using input stream and not URL

    Hi All,
    I looked over the docs and apis and I was not able to find any way to create a HelpSet from an input stream.
    Basically all I have is are input streams to the help files and not URLs, is there a way to initialize the help set with that?
    thanks

    Never compare Strings using Object equality or inequality ("==" resp. "!=").
    Use [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#equals(java.lang.Object)]String#equals (or [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String)]String#indexOf or [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#matches(java.lang.String)]String#matches).
    Please use code tags when posting code. This means wrapping your text between [code[/b]][[/b]code] tags. See the [url http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips.

Maybe you are looking for