Saving a JTextPane document to a file?

Hi,
I have a JTextPane that contains text with different colors(styles)
I was wondering if you know a way to easily save a document to a file in order to load it at a later time.
thanks !
Squid.

Look this link...
http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html

Similar Messages

  • Saving a styled document to XML file

    Hi,
    I am trying to save a styled document to an XML file, and I don't know how. I can easily save the text with writer.writeCharacters(string), where writer is an XMLStreamWriter. But how to save any style information?
    If I use XMLEncode do just dump out the document, how do I write the startElements, endElements, etc? Can I have two streams to the same file?
    Or is there a way to save the styling information separately from the text (attributes?) so that it automatically matches up when both text and styles are read back in?
    HEre is the code I currently use:
       // write cards.
                    final JFileChooser fc = new JFileChooser();
                  int returnVal = fc.showSaveDialog(null);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                     File saveFile = fc.getSelectedFile();
                     XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
                     try
                         FileWriter fileWriter=new FileWriter(saveFile);
                         XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter);
                         writer.writeStartDocument("1.0");
                         writer.writeStartElement("Deck");
                       FlashCard onecard;
                  for (int i=0; i < current.cards.size(); i++)
                           onecard=(FlashCard)current.cards.get(i); 
                           writer.writeStartElement("Card");
                           writer.writeStartElement("front");
                          writer.writeCharacters (onecard.front );
                          writer.writeEndElement();
                          writer.writeStartElement("back");
                          writer.writeCharacters (onecard.back );
                          writer.writeEndElement();
                          writer.writeEndElement();
                       writer.writeEndElement();
                       writer.flush();
                       writer.close();
                        current.nameDeck=saveFile.getName();
                      } This is in a flashcard program and I use XML to separate the different cards and the fronts and backs of each card.
    Marlon

    Here's what I did for that: the StyledDocument is a tree structure, so I traversed that structure recursively and built an XML document with the same structure, using SAX events.Element e = textPane.getDocument().getDefaultRootElement();
    SAXTransformerFactory tf = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
    TransformerHandler handler = tf.newTransformerHandler();
    Transformer t = handler.getTransformer();
    t.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "UTF-16");
    StringWriter sw = new StringWriter();
    handler.setResult(new StreamResult(sw));
    handler.startDocument();
    dumpElement(e, handler);
    handler.endDocument();And here's the dumpElement method that does the recursive business:private void dumpElement(Element e, ContentHandler ch) {
      try {
        AttributeSet as = e.getAttributes();
        AttributesImpl a = new AttributesImpl();
        Enumeration ase = as.getAttributeNames();
        while (ase.hasMoreElements()) {
          Object name = ase.nextElement();
          Object value = as.getAttribute(name);
          a.addAttribute("", "", name.toString(), "string", value.toString());
        ch.startElement("", "", "Element", a);
        int ec = e.getElementCount();
        if (ec == 0) {
          int start = e.getStartOffset();
          int len = e.getEndOffset() - start;
          if (start < textPane.getDocument().getLength()) {
            a = new AttributesImpl();
            a.addAttribute("", "", "Offset", "string", Integer.toString(start));
            try {
              ch.startElement("", "", "Text", a);
              String text = textPane.getDocument().getText(start, len);
              char[] textChars = new char[text.length()];
              text.getChars(0, text.length(), textChars, 0);
              ch.characters(textChars, 0, text.length());
              ch.endElement("", "", "Text");
            } catch(BadLocationException ble) {
        } else {
          for (int i=0; i<ec; i++) {
            dumpElement(e.getElement(i), ch);
        ch.endElement("", "", "Element");
      } catch(SAXException saxe) {
        saxe.printStackTrace();
    }You can adapt this to suit your requirements.

  • I cannot find my saved text edit documents after interrupting file vault, where did they go?

    Was file vault able to back up even though it was interrupted? Where does it go? Can I restore my computer to where it was before I tried using filevault? I think I have backed up my computer with iCloud previously.

    Is FileVault on or off?
    Do you have any backups besides what is being backed up to iCloud?

  • When I attempt to open a PDF file I saved from a website, I get the message "There was an error opening this document. The file is damaged and could not be repaired." Is there any way to correct this problem?

    When I attempt to open a PDF file I saved from a website using Safari, I get the message "There was an error opening this document. The file is damaged and could not be repaired." When I save the same PDF file using FireFox it opens up immediately. Is there any way to correct this problem with Safari?

    Back up all data.
    Triple-click the line of text below to select it, the copy the selected text to the Clipboard (command-C):
    /Library/Internet Plug-ins
    In the Finder, select
    Go ▹ Go to Folder
    from the menu bar, or press the key combination shift-command-G. Paste into the text box that opens (command-V), then press return.
    From the folder that opens, remove any items that have the letters “PDF” in the name. You may be prompted for your login password. Then quit and relaunch Safari, and test.
    The "Silverlight" web plugin distributed by Microsoft can also interfere with PDF display in Safari, so you may need to remove it as well, if it's present.
    If you still have the issue, repeat with this line:
    ~/Library/Internet Plug-ins
    If you don’t like the results of this procedure, restore the items from the backup you made before you started. Relaunch Safari again.

  • An internal error occurred while writing imported graphics in this document. The file has been saved

    An internal error occurred while writing imported graphics in this document. The file has been saved, but has lost some image data. Please report this error to Adobe Technical Support.
    How do i fix this, there are no images in the document
    thanks
    emma

    We are running FM version 7.2b144 on MS Win xp Pro (32 bit), and I did not notice this until service pack 3 was installed. I believe I have found a work around to the situation and another contributing cause. If graphic files are placed directly in an anchored frame instead of importing by reference, the file somehow becomes misplaced. If you right click the graphic and open the Object Properties dialog box, and see the phrase "no referenced file" below Main Editor: Referenced File: in the lower left hand corner, this has happened. I found if I removed all graphics files without references and imported them by reference, the source file may then be properly saved. I am also using a program called CCleaner, which removes cookies, temp files, browsing history and the like from a system. If the program settings are chosen too aggressively, and the application runs when FM has a file open, this same error will occur, even if all files are referenced properly. I don't know if SP3 has some similar application which is now running in the background and causing this.
    To summarize, if you want to retain SP3, I have eliminated this error by confirming the links to referenced graphics files and avoiding using 3rd party "cleaners" while FM is open.

  • I'm having a problem saving a pages document as another format, like a Word document or PDF file.  I've never had this problem in the past.  Please help me!  I need to have this fixed a.s.a.p.

    Hello everyone,
    I'm currently having a problem saving a Pages document as another format, such as a Word document or PDF file.  I've never had this problem before with Pages.  Please help me!  I need to have this completed a.s.a.p.
    Thanks,
    Amy

    To save as a PDF, you do that from Print
    To save as Wrod format, you export
    Allan

  • "The document 'Backup of Backup of Oral Report' could not be saved as 'Oral Report'. Bad file descriptor"

    Hello,
    Whenever I try to save my Keynote file, I receive an error message saying: "The document 'Backup of Backup of Oral Report' could not be saved as 'Oral Report'. Bad file descriptor".
    I've tried using other name to save my file, saving the file as a backup, saving it within my documents, and on a USB, but the file won't save. I'm using Keynote '09, Version 5.1.1 (1034) on my Mac Desktop running Mac OS X Version 10.6.8
    How can I fix this problem and save my file?

    change icloud backup to local backup on this compuet. this worked for me.

  • Saving documents with similar file names

    When saving documents with similar file names, I used to be able to hit save as button and go to the file folder I wish to use. I could then click an existing file in the folder to draw in the name and then just modify it slightly to create the new name.
    In Reader DC I get an error saying this is a read only file an can not be saved.  I can save the file if I use a different file name but then I have to go in and rename the file. i.e. if I have a weakly report that I save, I may have the file name "Installerspayroll.we.04.25.15.pdf."
    I used to be able to click on the existing file name to bring it into the name box and then just change the date. The updated version is not allowing me to do that, creating more work.

    I thought you were referring to an admin account within the Adobe program. I am an admin on the machine I am signed into and using while having these problems
    Thank you for this opportunity to share our expertise,
    Michael Mallary
    Treasurer
    Mallary Carpet & Flooring, Inc.
    410-766-6992
    www.mallarycarpet.com<http://www.mallarycarpet.com>
    Earning your unsolicited referrals
    is our number one priority

  • Word saving documents as binary files- can't send documents as attachments

    I've had my Macbook for about 9 months. During the first 6 months, I could send attachments via email perfectly fine. After about 6 months, something happened and the files could no longer be opened after being attached. I tried sending some attachments to myself and found out that the documents were being sent as binary files.
    I also backed up my documents onto an external hard drive. When I opened the documents on a Windows computer, the Word documents that I created during the first 6 months could be opened. However, the most recently created documents couldn't be opened by my computer.
    I decided to do an erase and install on Saturday. Afterwards, Word was working fine and I was able to send documents as attachments. This morning (Tuesday) I tried to send attachments again and it didn't work! Again, the documents were binary files.
    I'm not sure what to do because it was working fine for three days, but now it's not working anymore. I think something must have happened during those three days that corrupted my computer?
    Has anyone had a similar problem? Can anyone help?
    Sorry I know it was a long post but I wanted to give more information in case it would give some clues. I feel I should add that I've been having quite a few problems with my Macbook, e.g. screen freezing, DMGs not loading properly, getting some pop ups
    Message was edited by: MissIndecisive
    Also wanted to add that I've had my logicboard replaced recently because of problems such as freezing, so I don't think it should be a hardware problem.

    Since Word is not an Apple product, you'll get better response if you use a forum dedicated to Microsoft's Mac products such as <http://groups.google.com/groups/dir?sel=33607053> rather than an Apple forum that focuses on compatibility between Macs and Windows.
    Be sure to search the forum first in case someone has already had a similar question answered. You'll get your answer faster this way. Post your question in the forum if you don't find anything that helps you

  • I can't remember how to open a pdf file that I saved in My Documents.

    At one time I knew how to open a pdf saved in My Documents on my iMac, but I can't remember now. I need to open this document because it's for my taxes. Any help will be greatly appreciated.
    ~ Sue

    Care to share which OS you are using?

  • Can you export images which have been pasted into an Illustrator document as separate files?

    I have a multi-page Illustrator document (over 50 artboards) which contains lots of images that are all saved within the document (not linked in from seperate files) and all the images need to be exported as separate image files (similar to when you package a file in Indesign). The problem is the files are not linked, they are all saved within the document.
    Want to avoid having to copy + paste every image into a new document in Photoshop and save individually as this will take forever.

    Save the document as a PDF and Open in Photoshop. Select only the Images in the Open dialog and proceed from there.

  • Major problem saving and printing documents on two computers

    This is a bizarre problem that seems to have been transferred from my old MDD to my new Mini when I migrated all my old data and it has me baffled. My apologies if this explanation seems long and complicated but I want to be pretty thorough.
    About a month ago I started experiencing a problem with printing. I noticed when printing a sheet of business cards that the page was getting compressed, for lack of a better word, vertically. This was very noticeable because the trim marks on the side of the page were not lining up with the perforations and each row of cards was getting progressively closer to the top as each row was printed. In other words, the first row of cards was okay but then the next row was a little too far "north", the next row a little more, the next row a little more, etc. The bottom of the page was not cut off, it was just squeezed up a bit but not enough that you could tell that the proportions were off. Now I see that many of my documents are like that no matter what application I've use to create them – Pages, Illustrator, Avery DesignPro. What's even worse, I've used Pages to create a sheet of business cards for a friend and Illustrator to make packaging labels and she's having the same problem printing the PDFs of the labels on a different computer. What this seems to tell me is that something has been corrupted and the computer is saving messed up files.
    So, about ten days ago I got a Mini and migrated my data using Migration Assistant. And the problem has now been transferred to the Mini. So I now have two Macs connected to two different HP printers that are both incapable of printing (and apparently saving) documents in the proper proportions.
    Now, a truly weird thing is that I printed a test sheet of business cards from the Mini on the printer connected to the MDD (via printer sharing) and it appeared that the document printed at the correct length. However, another document, a sheet of labels created in Illustrator, printed at the right length but one edge was slightly cropped off. Grrr.
    Anyway, as I said, until about a month ago everything worked fine so something got messed up at that time to cause this problem with saving and printing documents. I need to get this resolved for business reasons – I'm an aspiring designer – but the only thing I can think of doing is wiping out my Mini and reloading everything except my account settings from Time Machine unless someone has advice on what to do. Help! (And yes, I've checked to see that page scaling was always set at 100%.)

    Well, I've just about had it. I erased the disk, reinstalled the OS, Adobe CS4, and iWork. I did not use Migration Assistant this time to restore my settings but still my Mac prints documents in the wrong dimensions. Could this be a sudden HP problem? It seems to me some system setting somewhere is making my computer save and print documents in the wrong size. I now have a computer that is almost useless for designing. Lucky me.

  • Can I Save a Single .AI Document As Multiple Files, Seperated by the Page Tiling?

    There must be a way to save or output a single Adobe Illustrator file  into multiple files based on the "pages" I have created in the  document?
    For example, if I have tiled 10 tabloid-sized  pages onto a single Illustrator CS3 .AI file, is it possible to save  the file in a manner that will allow all of those tiled pages to be  saved as a seperated or individual files?
    I guess it  would be a similar concept to how in newer versions (like CS4) you can  export multiple jpegs of an illustrator file that contains several  artboards and it automatically assigns a number suffix to the filename  since multiple files were outputted from the single ai file.
    Any  help is MUCH appreciated. Thanks!

    Please post your question in the Illustrator forum. This forum is for suite specific issues only.
    Bob

  • Billing document to flat file

    Hi,
    I have a scenario in which i need to create a flat file and store in a local folder upon saving a billing document. This flat file will have certain selected information from the VBRK/VBRP tables.
    This flat file will be read by another interface software to print a bar code so that the invoice from SAP along with bar code print has to be sent to a particular customer.
    I am not able to find any user exit (only upon saving billing document) so that I can program to trigger a flat file creation in local folder.
    Can any body help as to how to address this requirement?
    Regards

    Hi Karthik,
               Try with these User exits
    1.USEREXIT_PRINT_ITEM (Module pool SAPLV61A, (program RV61AFZB)
    2.USEREXIT_PRINT_HEAD (Modulpool SAPLV61A,     (Programm RV61AFZB)
    I hope it will help you
    Regards,
    Murali.

  • How to add/change Job Options when saving a FrameMaker document as a PDF using Acrobat 9

    If you are logged on as a domain user you could have a problem if you want to add or edit .joboption files in Distiller 9 when it is opened by FrameMaker.
    After installing Acrobat 9 the action of saving a FrameMaker document as a PDF automatically starts Distiller 9 which then uses the "Job Options" files that are located in C:\Documents and Settings\All Users\Application Data\Adobe\Adobe PDF\Settings. Unless some changes have been made to the "Security" settings of the "Adobe" folder and the "Adobe PDF" folder under "All Users" it will not be possible to add or edit ".joboption" files in the "Settings" folder located in that "Adobe PDF" folder.
    This can be confusing because when Distiller 9 is started separately, from Programs, it then uses the job options located in your own user folder (C:\Documents and Settings\NLPW\Application Data\Adobe\Adobe PDF\Settings). In your own user folder (in my case: NLPW) you can add or edit the job option files.
    In order to be able to add or edit job option files under "All Users" you must be included in the "All Users" list and have the appropriate "Permissions" security setting. To set this, right click on the "Adobe" folder (C:\Documents and Settings\All Users\Application Data\Adobe) and select "Properties", then click on the "Security" tab and add yourself to the list. Finally, (important) check the "Full Control" box under "Allow" in the permissions field. Repeat this procedure on the "Adobe PDF" folder (C:\Documents and Settings\All Users\Application Data\Adobe\Adobe PDF). Now you have the ability to add or edit ".joboption" files located in the "Settings" folder and these will be available when Distiller is started by FrameMaker.

    Thank you so much for that tip. I don’t have exactly the same set-up (FrameMaker 8, Acrobat 8 Professional), but changing the permissions as you describe fixed the problem of not being able to save or change Distiller job options which has been bothering me for a while.

Maybe you are looking for