Writing to file with ObjectOutputStream

ApartmentWriterProgram asks information about apartments
and saves it to a file.
For some reason it doesnt save information, it writes:
Writing to file "+file+ " failed.
So there happens IOException in the method write(Apartment apartment).
Or in the run().
I dont know what's wrong. Do you?
public class ApartmentFileHandler extends Object implements Serializable {
    private OutputStream outStream;
    private ObjectOutputStream obStream;
    private String filePath;
        public ApartmentFileHandler(String filePath) {
           this.filePath = filePath;
/** Writes the given apartment data in the file. If the file already
exists, the old contents are overwritten.
Parameters:
apartment - the apartment to be written in the file
Throws:
IOException - if other problems arose when handling the file (e.g. the
file could not be written)
        public void write(Apartment apartment)
           throws IOException {
           outStream = new FileOutputStream(filePath);
           obStream = new ObjectOutputStream(outStream);
           obStream.writeObject(apartment);
import java.io.*;
import java.util.*;
public class ApartmentWriterProgram
extends Object
    private KeyboardReader keyboardReader;
    private List roomsInList;
    private Room[] rooms;
    private int numberOfRooms;
    private String file;
          public ApartmentWriterProgram()
            this.keyboardReader = new KeyboardReader();
            this.roomsInList = new ArrayList();
            this.rooms = new Room [numberOfRooms];
/** Runs the writer program. The program asks the user for some
apartment data and a file name, and saves the data in the file. */
          public void run() {
            try {
              numberOfRooms = keyboardReader.getInt("Give number of rooms: ");
              for (int i =1; i<numberOfRooms+1; i++) {
                 String type =keyboardReader.getString("Give " +i+ ". " + "type of the room: ");
                 double area =keyboardReader.getDouble("Give " +i+ ". " + "area of room: ");
                 Room room= new Room(type, area);
                 this.roomsInList.add(huone);
              roomsInList.toArray(rooms);
              Apartment apartment = new Apartment(rooms);
              System.out.println();
              file = keyboardReader.getString("Give name of the file: ");
              ApartmentFileHandler handler = new ApartmentFileHandler(file);
              handler.write(apartment);
           } catch (IOException ioe) {
             System.out.println("Writing to file "+file+ " failed.");
         public static void main(String[]  args) {
              ApartmentWriterProgram program = new ApartmentWriterProgram();
              program.run();
}

There is nothing to gain in not putting the throws IOException in the write method, since the exception object will have the information about the actual problem.
Is this a typo for the this post?                 this.roomsInList.add(huone); should be room nes pas.
What exception is actually thrown? To find out useSystem.out.println("Exception: " + ioe);Then wonder why you have the AppartmentFileHandler implement Serializable when you are not writing that object to the file.

Similar Messages

  • Suppress writing cache files with rwrun.exe

    Hello,
    we`re using rwrun.exe (9.0.4.2.0) with parameters to create pdf-files in a loop:
    REPORT=mytest.rdf
    USERID=scott/tiger@orcl
    BLANKPAGES=no
    DESTYPE=file
    DESNAME=mytest.pdf
    DESFORMAT=PDF
    OUTPUTIMAGEFORMAT=GIF
    CACHELOB=NO
    Each process write a cache file in the directory …\reports\cache. Reports eats the hard disk :-(
    I`ve found the EXPIRATION command in the documentation, which defines the point in time when the report output should be deleted from the cache. But this command strictly runs with rwclient.exe and reports server, but Reports server isn`t installed on our server.
    Can we suppress writing cache files with rwrun.exe?
    Steffen

    Hello,
    Why don't you add a command del in your loop ?
    Example:
    del %ORACLE_HOME%\reports\cache\*.*
    Regards

  • Writing Datalog Files with record length

    How do I write a Datalog File with a record length of 128 int16s?

    Each I16 number in LabVIEW that you write uses 2 bytes because 8 bits equals 1 byte. If you write 128 numbers, the file will be 256 bytes long. You can modify the VI to write I32 (4 bytes) or I8 (1 byte) just by changing the representation of the number. You also need to change the subVI that does the actual writing (Write File+ [I16].vi). Be sure to rename the VIs that you change. I would think that your Fortran program would work as long as the data types match.

  • Trouble writing to file with FileWriter

    Hey I'm pretty new to Java and even newer to file classes so I'd appreciate it you could look over what I've done. My FlashCard object has its own toString() method which prints out what I want it to so basically all I need to know is why it doesn't print anything?
    File f;
    //..Constructors and other methods for a JFrame
         private void printList() throws IOException
                   writer = new PrintWriter(new BufferedWriter(new FileWriter(f)), true); //f is a File object declared below
                   writer.println("test");
                   java.util.Iterator<FlashCard> e = cards.iterator();
                   String s = "";
                   while(e.hasNext())
                        s = "" + e.next();
                        writer.println(s);          
                        System.out.println(s);   //Debugging line, prints out what i want to be put in the file correctly!
                   writer.close();
                   FileWriter writer2 = new FileWriter(f, true);
                   writer2.write("hi");
    //....more code
    private class ClickListener                          //subclass of the class containing the code above
                   implements ActionListener
                   @Override
                   public void actionPerformed(ActionEvent e)
                        if (e.getSource() == create)
                             boolean temp = false;
                             String fileName = "c:\\FlashCards\\";
                             f = new File(fileName);
                             f.mkdir();
                             f = new File(fileName + stackName.getText() + ".txt");
                             try {
                                  temp = f.createNewFile();
                             } catch (IOException e1) {
                             //...More code here for responding to file not being created successfully
                             f.setWritable(true);
                             control.currentFile = f;
                        }This the the only code I thought to be relevant but if there's a declaration you need that I left out let me know! The annoying thing is I copied this from another class I wrote (with modifications of course) and it works perfectly, no problems!
    Thanks in advance!

    OK I've done the things you've mentioned, thank you for me notice i was missing some code organization. The problem unfortunately is not yet solved but now I think I have a better idea of what the problem is! Here's the code:
    This is what I'm using to make a file
    private void createFile()
                   boolean temp = false;
                   String fileName = "c:\\FlashCards\\";
                   f = new File(fileName);
                   f.mkdir();
                   f = new File(fileName + stackName.getText() + ".txt");
                   try {
                        temp = f.createNewFile();
                   } catch (IOException e1) {
                        //TODO fill in exception catchs
                   if(temp)
                        //Do something
                   else
                        JOptionPane.showMessageDialog(addCard, "File Name Already Exists");
                        return;
              }And this is where the file is being used by a writer:
              private void printList() throws IOException
                   String temp = f.getAbsolutePath();
                   PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File(temp), true)), true);
                   java.util.Iterator<FlashCard> i = cards.iterator();
                   while(i.hasNext())
                        writer.println(i.next());          //TODO fix this writer so that it prints properly onto the document!!
                   writer.close();
              }The problem I think is either caused by a) the new File doesn't like properly to the FileWriter for some reason or b) the file I've made does not work for output for some reason. I think this because I can make a new file with a literal pathname such as "c:\\file.txt" and it works fine but as soon as I use my file f to make it it doesn't print anything out!! any ideas?

  • Writing a file with the OutputStream

    I'm trying to upload a file using Java's included ftp functionality.
    currently I'm trying to figure out how to upload a file. The connection and works.
    The code I found for the ftp connection indicated that I should use the following code to upload..
    URLConnection urlc = url.openConnection();
    OutputStream os = urlc.getOutputStream();
    I've read the documentation for the outputstream and looked for help tutorials on the web etc, but still haven't been able to figure out what I'm doing.
    I need the output stream to write a file to the ftp server. I can get it to put a file there, but so far its just been an empty file. How do I get it to actually write the file with its contents etc.
    thanks for the help

    never mind :) I think I figured it out.
    I just created a File object for the file, then opened a fileinputstream to read the file in and wrote that output using the output stream.
    it seems to work.

  • Writing to file with specific encoding in unix

    hi,
    I want to write html files which contain Turkish characters in unix operating system.
    I'm currently using FileWriter to write the files.
    I'm getting the file content from the database and I can see that the characters seem to be fine but when I write them into an html file, they are displayed with the question mark character (?).
    What can I do about this?
    Thanks

    FileWriter uses the default character encoding of whatever platform your program is running on. Beside the fact that the default encoding may vary from one machine to another, it may not be suitable for storing non-ASCII (Turkish) characters.
    Rather than using FileWriter, you can use an OutputStreamWriter and a FileOutputStream, which allows you to specify the character encoding you want. UTF-8 is generally a good choice, since it can encode just about anything. For example:FileOutputStream fos = new FileOutputStream("/some/file/name");
    OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
    osw.write("your text with Turkish characters...");Geoff

  • Issues writing to file with Jython

    Hi all,
    I want to write into a file the message of the previous step.
    We have created a procedure but we get this error below.
    How could we manage the <%=odiRef.getPrevStepLog("MESSAGE")%> in order to be written into the file?
    I guess we would have to replace but don't know what
    org.apache.bsf.BSFException: exception from Jython:
    Traceback (innermost last):
    (no code object) at line 0
    SyntaxError: ('Lexical error at line 6, column 123. Encountered: "\\n" (10), after : ""', ('<string>', 6, 123, "strMessage = '3290 : 42000 : java.sql.SQLException: ORA-03290: Invalid truncate command - missing CLUSTER or TABLE keyword"))
         at org.apache.bsf.engines.jython.JythonEngine.exec(JythonEngine.java:146)
         at com.sunopsis.dwg.codeinterpretor.k.a(k.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.scripting(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.execScriptingOrders(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.execScriptingOrders(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTaskTrt(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSqlS.treatTaskTrt(SnpSessTaskSqlS.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java)
         at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandSession.treatCommand(DwgCommandSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandBase.execute(DwgCommandBase.java)
         at com.sunopsis.dwg.cmd.e.i(e.java)
         at com.sunopsis.dwg.cmd.h.y(h.java)
         at com.sunopsis.dwg.cmd.e.run(e.java)
         at java.lang.Thread.run(Unknown Source)
    The description of the error is:
    3290 : 42000 : java.sql.SQLException: ORA-03290: Invalid truncate command - missing CLUSTER or TABLE keyword
    java.sql.SQLException: ORA-03290: Invalid truncate command - missing CLUSTER or TABLE keyword
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:316)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:282)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:639)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:185)
         at oracle.jdbc.driver.T4CPreparedStatement.execute_for_rows(T4CPreparedStatement.java:633)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1086)
         at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:2984)
         at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3057)
         at com.sunopsis.sql.SnpsQuery.executeUpdate(SnpsQuery.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.execStdOrders(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTaskTrt(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSqlS.treatTaskTrt(SnpSessTaskSqlS.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java)
         at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandSession.treatCommand(DwgCommandSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandBase.execute(DwgCommandBase.java)
         at com.sunopsis.dwg.cmd.e.i(e.java)
         at com.sunopsis.dwg.cmd.h.y(h.java)
         at com.sunopsis.dwg.cmd.e.run(e.java)
         at java.lang.Thread.run(Unknown Source)
    Thanks

    There is nothing to gain in not putting the throws IOException in the write method, since the exception object will have the information about the actual problem.
    Is this a typo for the this post?                 this.roomsInList.add(huone); should be room nes pas.
    What exception is actually thrown? To find out useSystem.out.println("Exception: " + ioe);Then wonder why you have the AppartmentFileHandler implement Serializable when you are not writing that object to the file.

  • Duplicate namespace declarations when writing a file with JCA file adapter

    I am using JCA File adapter to write a an XML file. The composite contains a mediator which received and transforms an XML to desired format and then calls a JCA file adapter to write the file.
    The problem that I am having is that the written file has declaration of namespaces repeated with repeating elements instead of a single declaration at root. For ex.
    instead of
    <ns0:Root xmlns:ns0="namespace0"  xmlns:ns1="namespace1" xmlns:ns2="namespace2">
    <ns0:RepeatingChild>
    <ns1:Element1>value1</ns1:Element1>
    <ns2:Element2>value2</ns2:Element2>
    </ns0:RepeatingChild>
    <ns0:RepeatingChild>
    <ns1:Element1>value3</ns1:Element1>
    <ns2:Element2>value4</ns2:Element2>
    </ns0:RepeatingChild>
    </ns0:Root>What I see in the file is:
    <ns0:Root xmlns:ns0="namespace0"  xmlns:ns1="namespace1" xmlns:ns2="namespace2">
    <ns0:RepeatingChild>
    <ns1:Element1 xmlns:ns1="namespace1" xmlns:"namespace1">value1</ns1:Element1>
    <ns2:Element2 xmlns:ns2="namespace2" xmlns:"namespace2">>value2</ns2:Element2>
    </ns0:RepeatingChild>
    <ns0:RepeatingChild>
    <ns1:Element1 xmlns:ns1="namespace1" xmlns:"namespace1">>value3</ns1:Element1>
    <ns2:Element2 xmlns:ns2="namespace2" xmlns:"namespace2">>value4</ns2:Element2>
    </ns0:RepeatingChild>
    </ns0:Root>So basically all the elements which are in different namespace than root element have a namespace declaration repeated even though the namespace identifier is declared at the root elment level.
    Although, the XML is still valid, but this is unnecessarily increasing the filesizes 3-4 times. Is there a way I can write the XML file without duplicate declarations of namespaces?
    I am using SOA Suite 11.1.1.4
    The file adapter has the schema set as above XML.
    I tried the transformation in mediator using XSL and also tried using assign [source(input to mediator) and target(output of mediator, input of file adapter) XMLs are exactly same].
    but no success.

    I used automapper of JDeveloper to generate the schema. The source and target schema are exactly same.
    I was trying to figure it out and I observed that if the namespaces in question are listed in exclude-result-prefixes list in xsl, then while testing the XSL in jDeveloper duplicate namespaces occur in the target and if I remove the namespace identifiers from the exclude-result-prefixes list then in jDeveloper testing the target correctly has only a single namespace declaration at the root node.
    But, when I deployed the same to server and tested there, again the same problem.

  • PDF file transfer writing target file with the same source file name

    Hi to all,
    I want to transfer a PDF file from a SOURCE folder to a TARGET folder. My problem is that I want the target pdf file has the same name of the source pdf file. How can I do this? I have to look for some parameters in the sender or receiver channels?
    Thanks to all.

    Hi Gabriele,
    If you want to FTP the pdf file from source to target directory, use this blog.  It doesn't require any IR devlopment.
    /people/william.li/blog/2006/09/08/how-to-send-any-data-even-binary-through-xi-without-using-the-integration-repository
    Also, In sender and receiver comm channels select "Set/Use Adapter specific message attributes" and "File Name" to get the same file name in the target directory.
    Regards,
    Sreenivas

  • Access denied error while writing a file to the file system - myfileupload.saveas() throws system.unauthorizedexception

    hi,
    as part of my requirement , i have to perform read and  write  operations of  few files [ using the file upload control in my custom visual web part] and on submit button click.
    but while writing these files - with the help of  fileupload control - and when i use  myfileupload.saveas(mylocation);
    - i am saving these files into my D:\ drive of my server , where i am executing my code -, am getting access denied error.
    it throws system.unauthorizedexception.
    i have given full control on that folder where i was trying to store my attached files. and also  after following asp.net forums,
    i have added  iusr group added and performed all those steps such that, the file is saved in my D:\ drive.
    but unfortunately  that didnt happen.
    also
    a) i am trying the code with runwithelevatedprivileges(delegate() )  code
    b) shared the drive within the  d :drive where i want o save the files.
    c) given the full privieleges for the app pool identity- in my case , its
    network service.
    the  other strange thing is that, the same code works perfectly in  other machine, where the same sp, vs 2012  etc were installed .
    would like to know, any other changes/ steps i need to make it on this  server, where i am getting the  error.
    help is  appreciated!

    vishnuS1984 wrote:
    Hi Friends,
    I have gone through scores of examples and i am failing to understand the right thing to be done to copy a file from one directory to another. Here is my class...So let's see... C:\GetMe1 is a directory on your machine, right? And this is what you are doing with that directory:
    public static void copyFiles(File src, File dest) throws IOException
    // dest is a 'File' object but represents the C:\GetMe1 directory, right?
    fout = new FileOutputStream (dest);If it's a directory, where in your code are you appending the source file name to the path, before trying to open an output stream on it? You're not.
    BTW, this is awful:
    catch (IOException e)
    IOException wrapper = new IOException("copyFiles: Unable to copy file: " +
    src.getAbsolutePath() + "to" + dest.getAbsolutePath()+".");
    wrapper.initCause(e);
    wrapper.setStackTrace(e.getStackTrace());
    throw wrapper;
    }1) You're hiding the original IOException and replacing it with your own? For what good purpose?
    2) Even if you had a good reason to do that, this would be simpler and better:
    throw new IOException("your custom message goes here", e);
    rather than explicitly invokign initCause and setStackTrace. Yuck!

  • Memory issues writing binary files, using a subVI to do all File Handling, topVI, when run normally files are way too large.

    Problem writing binary files with LV 8.5. I have one VI that does all the interaction/file I/O and another VI for testing. I find when I run the subVI where all the data reading/writing is happening with break points and single stepping through the code all is OK, but when I run normally the files are much larger than they should be and as well when I close the files I get a error. Any insights?  
    Walter

    Waltz wrote:
    I found the problem, I was actually trying to close the files twice.
    I don't see how this could cause the symptoms you described in the first post.
    (It only explains the error on close).
    LabVIEW Champion . Do more with less code and in less time .

  • How To read an XML file with JDom

    I have read through some tutorials after installing JDom on how to read an existing XML file and I was confused by all of them. I simply want to open an XML file and read one of the node's content. Such as <username>john doe</username> this way I can compare values with what the user has entered as their username. I am not sure were to start and I was hoping someone could help me out.
    I know that this seems like an insecure way to store login information but after I master opening and writing XML files with JDom I am going to use AES to encrypt the XML files.

    Here is a test program for JDom and XPath use considering your XML file is named "test.xml" :import org.jdom.input.*;
    import org.jdom.xpath.*;
    public class JDomXPath {
    public static void main(String[] args) {
      SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
      try {
       org.jdom.Document jdomDocument = saxBuilder.build("test.xml");
       org.jdom.Element usernameNode = (org.jdom.Element)XPath.selectSingleNode(jdomDocument, "//username");
       System.out.print(usernameNode.getText());
      } catch (Exception e) {
       e.printStackTrace();
    }(tested with Eclipse)

  • How can I make waveform graph and/or excel file with two different dynamic DBL values?

    As the question describes, I have two dbl sources from a load cell and linear actuator (from firgelli). I want to make a load/displacement curve from the force readings from the load cell and the displacement readings from the linear actuator. The load cell outputs an analog signal that can be acquired by a DAQ and the actuator comes in with a board and VI program to control the speed and measure the displacement of the actuator to a sample rate of my choosing. Is there a way that I can make a VI where it continues to collect data and construct the graph I'm looking for?
    Solved!
    Go to Solution.

    A couple points about your application:
    1.  Synchronization.  Since you're ultimate goal is a stress/strain curve, it is vital that your force and displacement data be synchronized appropriately.  If your sampling is beyond a few times a second, this is not really possible without some form of hardware synchronization via either a trigger and/or sample clock.  Two NI DAQ boards can be synchronized this way easily, but it seems you're using 3rd party hardware for one of these processes.  Would need to know more about that board to know what options you have.  You could specify what your resolution is in distance, and how fast the article will be moving, to get an idea of how fast to acquire, and how well you'll need to synchronize the data.  Another option, since it appears each data stream will be sampled on a hardware-timed sample clock, they will be offset in time, but not skewed during the acquisition.  You may be able to identify a feature in the data set common to each and use that to remove the timing offset after the process is completed.
    2.  Display.  To display data during the acquisition process, I usually recommend at least one display that plots vs. time.  Much easier to spot irregularities with the acquisition process that way.  However, if you'd like to also plot force vs. displacement, you can use an XY Graph to plot parametrically. For Example, in your case you would use the Displacement data as the X coordinates, and the Force data as the Y coordinates.
    3.  Saving data to file.  I would recommend using the Save to Spreadsheet File.vi (File IO pallette) to save your data.  If you use a comma as the delimiter, and save the file with a *.csv extension, you will have a file that is easily read into excel.  The standard tab-delimited spreadsheet file is also fine, it will just require an extra step to read it into excel to specify to excel what the delimiter is.
    4.  Batch vs. Real-Time Recording (Data File).  If your process is short (< 30 sec) you may be better off acquiring the data, Storing it locally to the VI (Array - usually maintained in a shift register), and then writing the file with a header (acquisition parameters, test article information, data column headers) and the data all at once in batch mode to the file after the process is finished.  If, however, it is longer than that you would be better off starting a data file with a header and appending the data to the file as you go, so that if something happens during your test, you at least have data up to that point.
    Hope this Helps,
    Kurt

  • Writing a java program for generating .pdf file with the data of MS-Excel .

    Hi all,
    My object is write a java program so tht...it'll generate the .pdf file after retriving the data from MS-Excel file.
    I used POI HSSF to read the data from MS-Excel and used iText to generate .pdf file:
    My Program is:
    * Created on Apr 13, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package forums;
    import java.io.*;
    import java.awt.Color;
    import com.lowagie.text.*;
    import com.lowagie.text.pdf.*;
    import com.lowagie.text.Font.*;
    import com.lowagie.text.pdf.MultiColumnText;
    import com.lowagie.text.Phrase.*;
    import net.sf.hibernate.mapping.Array;
    import org.apache.poi.hssf.*;
    import org.apache.poi.poifs.filesystem.*;
    import org.apache.poi.hssf.usermodel.*;
    import com.lowagie.text.Phrase.*;
    import java.util.Iterator;
    * Generates a simple 'Hello World' PDF file.
    * @author blowagie
    public class pdfgenerator {
         * Generates a PDF file with the text 'Hello World'
         * @param args no arguments needed here
         public static void main(String[] args) {
              System.out.println("Hello World");
              Rectangle pageSize = new Rectangle(916, 1592);
                        pageSize.setBackgroundColor(new java.awt.Color(0xFF, 0xFF, 0xDE));
              // step 1: creation of a document-object
              //Document document = new Document(pageSize);
              Document document = new Document(pageSize, 132, 164, 108, 108);
              try {
                   // step 2:
                   // we create a writer that listens to the document
                   // and directs a PDF-stream to a file
                   PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream("c:\\weeklystatus.pdf"));
                   writer.setEncryption(PdfWriter.STRENGTH128BITS, "Hello", "World", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
    //               step 3: we open the document
                             document.open();
                   Paragraph paragraph = new Paragraph("",new Font(Font.TIMES_ROMAN, 13, Font.BOLDITALIC, new Color(0, 0, 255)));
                   POIFSFileSystem pofilesystem=new POIFSFileSystem(new FileInputStream("D:\\ESM\\plans\\weekly report(31-01..04-02).xls"));
                   HSSFWorkbook hbook=new HSSFWorkbook(pofilesystem);
                   HSSFSheet hsheet=hbook.getSheetAt(0);//.createSheet();
                   Iterator rows = hsheet.rowIterator();
                                  while( rows.hasNext() ) {
                                       Phrase phrase=new Phrase();
                                       HSSFRow row = (HSSFRow) rows.next();
                                       //System.out.println( "Row #" + row.getRowNum());
                                       // Iterate over each cell in the row and print out the cell's content
                                       Iterator cells = row.cellIterator();
                                       while( cells.hasNext() ) {
                                            HSSFCell cell = (HSSFCell) cells.next();
                                            //System.out.println( "Cell #" + cell.getCellNum() );
                                            switch ( cell.getCellType() ) {
                                                 case HSSFCell.CELL_TYPE_STRING:
                                                 String stringcell=cell.getStringCellValue ()+" ";
                                                 writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                 phrase.add(stringcell);
                                            // document.add(new Phrase(string));
                                                      System.out.print( cell.getStringCellValue () );
                                                      break;
                                                 case HSSFCell.CELL_TYPE_FORMULA:
                                                           String stringdate=cell.getCellFormula()+" ";
                                                           writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                           phrase.add(stringdate);
                                                 System.out.print( cell.getCellFormula() );
                                                           break;
                                                 case HSSFCell.CELL_TYPE_NUMERIC:
                                                 String string=String.valueOf(cell.getNumericCellValue())+" ";
                                                      writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                      phrase.add(string);
                                                      System.out.print( cell.getNumericCellValue() );
                                                      break;
                                                 default:
                                                      //System.out.println( "unsuported sell type" );
                                                      break;
                                       document.add(new Paragraph(phrase));
                                       document.add(new Paragraph("\n \n \n"));
                   // step 4: we add a paragraph to the document
              } catch (DocumentException de) {
                   System.err.println(de.getMessage());
              } catch (IOException ioe) {
                   System.err.println(ioe.getMessage());
              // step 5: we close the document
              document.close();
    My Input from MS-Excel file is:
         Planning and Tracking Template for Interns                                                                 
         Name of the Intern     N.Kesavulu Reddy                                                            
         Project Name     Enterprise Sales and Marketing                                                            
         Description     Estimated Effort in Hrs     Planned/Replanned          Actual          Actual Effort in Hrs     Complexity     Priority     LOC written new & modified     % work completion     Status     Rework     Remarks
    S.No               Start Date     End Date     Start Date     End Date                                        
    1     setup the configuration          31/01/2005     1/2/2005     31/01/2005     1/2/2005                                        
    2     Deploying an application through Tapestry, Spring, Hibernate          2/2/2005     2/2/2005     2/2/2005     2/2/2005                                        
    3     Gone through Componentization and Cxprice application          3/2/2005     3/2/2005     3/2/2005     3/2/2005                                        
    4     Attend the sessions(tapestry,spring, hibernate), QBA          4/2/2005     4/2/2005     4/2/2005     4/2/2005                                        
         The o/p I'm gettint in .pdf file is:
    Planning and Tracking Template for Interns
    N.Kesavulu Reddy Name of the Intern
    Enterprise Sales and Marketing Project Name
    Remarks Rework Status % work completion LOC written new & modified Priority
    Complexity Actual Effort in Hrs Actual Planned/Replanned Estimated Effort in Hrs Description
    End Date Start Date End Date Start Date S.No
    38354.0 31/01/2005 38354.0 31/01/2005 setup the configuration 1.0
    38385.0 38385.0 38385.0 38385.0 Deploying an application through Tapestry, Spring, Hibernate
    2.0
    38413.0 38413.0 38413.0 38413.0 Gone through Componentization and Cxprice application
    3.0
    38444.0 38444.0 38444.0 38444.0 Attend the sessions(tapestry,spring, hibernate), QBA 4.0
                                       The issues i'm facing are:
    When it is reading a row from MS-Excel it is writing to the .pdf file from last cell to first cell.( 2 cell in 1 place, 1 cell in 2 place like if the row has two cells with data as : Name of the Intern: Kesavulu Reddy then it is writing to the .pdf file as Kesavulu Reddy Name of Intern)
    and the second issue is:
    It is not recognizing the date format..it is recognizing the date in first row only......
    Plz Tell me wht is the solution for this...
    Regards
    [email protected]

    Don't double post your question:
    http://forum.java.sun.com/thread.jspa?threadID=617605&messageID=3450899#3450899
    /Kaj

  • SharePoint Designer 2013 after installation getting error with runtime i.e. error writing to file Microsoft.SharePoint.Client.Runtime.Local.Resources.dll Verify that you have access to that directory

    SharePoint Designer 2013 after installation getting error with runtime i.e. error writing to file Microsoft.SharePoint.Client.Runtime.Local.Resources.dll Verify that you have access to that directory
    after retry..again SharePoint Designer requires the following component require to install Microsoft.NET framework version 4 i have downloaded and try to installed but fail not work please answer what to do?
    Thanks and Regards, Rangnath Mali

    Hi Rangnath,
    For running SharePoint Designer 2013, you need to install Microsoft .NET 4.0 Framework or higher.
    Please uninstall the Microsoft .NET 4.0 Framework, and install it again. After that, reboot your machine.
    Best Regards,
    Wendy
    Wendy Li
    TechNet Community Support

Maybe you are looking for

  • How to access Mac disks in Windows

    hi i format my external harddrive for time machine to back up , however when i plug it in into my window ... it won''t regconize it ( i do have some back up form work in it as well) how do i access mac disks in window ? can anyone help ?

  • Home Movies over Apple TV

    Greetings: I have a significant amount of home movies on my windows computer in AVI format.  I want to save a copy of all AVI files.  I also have Quicktime Pro. What is the most efficient (space saving with best resolution) way of playing the AVI mov

  • Cast and Crew Credits

    Quick question... I hope... How do I add "Cast and Crew" credits to my home movies to be the same as purchased "Hollywood" movies? I have had a look in the "get info" sections for purchased movies in order to use the same sections for my details, but

  • Error adding other root certs to Weblogic

    I am using the trial 30-day version. I wonder whether it has any restrictions which prevent from adding new root certificates to the ca.pem file. If this is not the case, I will expose my problem. I have added a new self-signed root certificate after

  • AppV5 SP3 DB scripts

    Hi, It seems to have little bug in "InsertVersionInfo.sql" -script? Why it tries to write some version info to table (dbo.SchemaChanges) what doesnt exist at all "ManagementServer" db ? (Fresh new installation)