Writing Contents Of TreeSet To File

I am still a student of Java, so forgive me for the elementary question.
Is it possible to write the contents of a TreeSet to a File?
I would also like to be able to save the TreeSet in binary form instead of having it disappear when the program is closed. I think I need Serializable for this task.
The program I am trying to develop is for storing film titles. They need to be retrieved at program start-up. So far I have been able to have the titles go directly into the TreeSet from a JTextField with the click of a JButton. But obviously they are only in temporary memory and need to be saved to disk.
Thanks for any help.

> Is it possible to write the contents of a TreeSet to
a File?
Sure, writing text to a file: http://javaalmanac.com/egs/java.io/WriteToFile.html
> I would also like to be able to save the TreeSet in
binary form instead of having it disappear when the
program is closed. I think I need Serializable for
this task.
Correct. Check out this link: http://javaalmanac.com/egs/java.io/SerializeObj.html
> The program I am trying to develop is for storing
film titles. They need to be retrieved at program
start-up. So far I have been able to have the titles
go directly into the TreeSet from a JTextField with
the click of a JButton. But obviously they are only
in temporary memory and need to be saved to disk.
Wouldn't you prefer a Map (key/value pair) over a Set? With a map you can store the fim title as a key and create your own Movie object which stores director, year, actors/actresses etc. as the value.
See: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html
Good luck.

Similar Messages

  • How to write the JTables Content into the CSV File.

    Hi Friends
    I managed to write the Database records into the CSV Files. Now i would like to add the JTables contend into the CSV Files.
    I just add the Code which Used to write the Database records into the CSV Files.
    void exportApi()throws Exception
              try
                   PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
                   System.out.println("Connected");
                   stexport=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                   rsexport=stexport.executeQuery("Select * from IssuedBook ");
                   ResultSetMetaData md = rsexport.getMetaData();
                   int columns = md.getColumnCount();
                   String fieldNames[]={"No","Name","Author","Date","Id","Issued","Return"};
                   //write fields names
                   String rec = "";
                   for (int i=0; i < fieldNames.length; i++)
                        rec +='\"'+fieldNames[i]+'\"';
                        rec+=",";
                   if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
                   writing.println(rec);
                   //write values from result set to file
                    rsexport.beforeFirst();
                   while(rsexport.next())
                        rec = "";
                         for (int i=1; i < (columns+1); i++)
                             try
                                    rec +="\""+rsexport.getString(i)+"\",";
                                    rec +="\""+rsexport.getInt(i)+"\",";
                             catch(SQLException sqle)
                                  // I would add this System.out.println("Exception in retrieval in for loop:\n"+sqle);
                         if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
                        writing.println(rec);
                   writing.close();
         }With this Same code how to Write the JTable content into the CSV Files.
    Please tell me how to implement this.
    Thank you for your Service
    Jofin

    Hi Friends
    I just modified my code and tried according to your suggestion. But here it does not print the records inside CSV File. But when i use ResultSet it prints the Records inside the CSV. Now i want to Display only the JTable content.
    I am posting my code here. Please run this code and find the Report.csv file in your current Directory. and please help me to come out of this Problem.
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class Exporting extends JDialog implements ActionListener
         private JRadioButton rby,rbn,rbr,rbnore,rbnorest;
         private ButtonGroup bg;
         private JPanel exportpanel;
         private JButton btnExpots;
         FileReader reading=null;
         FileWriter writing=null;
         JTable table;
         JScrollPane scroll;
         public Exporting()throws Exception
              setSize(550,450);
              setTitle("Export Results");
              this.setLocation(100,100);
              String Heading[]={"BOOK ID","NAME","AUTHOR","PRICE"};
              String records[][]={{"B0201","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0202","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0203","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0204","PRIAM","SELVI","1354"},
                               {"B0205","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0206","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0207","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0208","PRIAM","SELVI","1354"}};
              btnExpots= new JButton("Export");
              btnExpots.addActionListener(this);
              btnExpots.setBounds(140,200,60,25);
              table = new JTable();
              scroll=new JScrollPane(table);
              ((DefaultTableModel)table.getModel()).setDataVector(records,Heading);
              System.out.println(table.getModel());
              exportpanel= new JPanel();
              exportpanel.add(btnExpots,BorderLayout.SOUTH);
              exportpanel.add(scroll);
              getContentPane().add(exportpanel);
              setVisible(true);
          public void actionPerformed(ActionEvent ae)
              Object obj=ae.getSource();
              try {
              PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
              if(obj==btnExpots)
                   for(int row=0;row<table.getRowCount();++row)
                             for(int col=0;col<table.getColumnCount();++col)
                                  Object ob=table.getValueAt(row,col);
                                  //exportApi(ob);
                                  System.out.println(ob);
                                  System.out.println("Connected");
                                  String fieldNames[]={"BOOK ID","NAME","AUTHOR","PRICE"};
                                  String rec = "";
                                  for (int i=0; i <fieldNames.length; i++)
                                       rec +='\"'+fieldNames[i]+'\"';
                                       rec+=",";
                                  if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
                                  writing.println(rec);
                                  //write values from result set to file
                                   rec +="\""+ob+"\",";     
                                   if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
                                   writing.println(rec);
                                   writing.close();
         catch(Exception ex)
              ex.printStackTrace();
         public static void main(String arg[]) throws Exception
              Exporting ex= new Exporting();
    }Could anyone Please modify my code and help me out.
    Thank you for your service
    Cheers
    Jofin

  • Help With Writing A Vector To A File

    hi
    i am having trouble writing a vector to a file
    Here is my code
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.filechooser.*;
    public class Save
         JFileChooser fc = new JFileChooser();
         public Save(JFrame par, mainCollection col)
         try
         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream fc.getSelectedFile().getName()));
         out.writeObject(col.carCollection);
         for(int i = 0; i< col.carCollection.size();i++)
         Cars cd = (Cars)col.carCollection.elementAt(i);
         Vector v = cd.getModels();
         out.writeObject(v);
         }catch(FileNotFoundException e){System.out.println("not found");}
         catch(IOException e){System.out.println("IO" + e.getMessage());}
    Ok now the mainCollection col is from my other class mainCollection which has my main vector in it. This main vector contains car types which contain car models i.e. Ford which contains Falcon. What i need to do is copy the whole contents of vector over in one go to the file.
    With the code above i am getting IO Exception errors
    here is the errors
    �� sr java.util.Vector��}[�;� I capacityIncrementI elementCount[ elementDatat [Ljava/lang/Object;xp       ur [Ljava.lang.Object;��X�s)l  xp  
    {sr  java.io.NotSerializableException(Vx ��5  xr java.io.ObjectStreamExceptiond��k�9��  xr java.io.IOExceptionl�sde%��  xr java.lang.Exception��>;�  xr java.lang.Throwable��5'9w�� L
    detailMessaget Ljava/lang/String;xpt Cars
    Whatever all that means
    Thanks for your help, i'm really confused
    DaJavaLodown
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Remove the for loop.
    If you write the vector, it's content will be written too.
    hi
    i am having trouble writing a vector to a file
    Here is my code
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.filechooser.*;
    public class Save
         JFileChooser fc = new JFileChooser();
         public Save(JFrame par, mainCollection col)
         try
    ObjectOutputStream out = new
    = new ObjectOutputStream(new FileOutputStream
    fc.getSelectedFile().getName()));
         out.writeObject(col.carCollection);
    for(int i = 0; i<
    = 0; i< col.carCollection.size();i++)
    Cars cd =
         Cars cd = (Cars)col.carCollection.elementAt(i);
         Vector v = cd.getModels();
         out.writeObject(v);
    }catch(FileNotFoundException
    ion e){System.out.println("not found");}
    catch(IOException e){System.out.println("IO" +
    " + e.getMessage());}
    Ok now the mainCollection col is from my other class
    mainCollection which has my main vector in it. This
    main vector contains car types which contain car
    models i.e. Ford which contains Falcon. What i need to
    do is copy the whole contents of vector over in one go
    to the file.
    With the code above i am getting IO Exception errors
    here is the errors
    �� sr java.util.Vector��}[�;� I
    capacityIncrementI elementCount[ elementDatat
    [Ljava/lang/Object;xp       ur
    r [Ljava.lang.Object;��X�s)l  xp  
    {sr  java.io.NotSerializableException(Vx ��5  xr
    java.io.ObjectStreamExceptiond��k�9��  xr
    java.io.IOExceptionl�sde%��  xr
    r java.lang.Exception��>;�  xr
    java.lang.Throwable��5'9w�� L
    detailMessaget Ljava/lang/String;xpt Cars
    Whatever all that means
    Thanks for your help, i'm really confused
    DaJavaLodown

  • Sorting file content of a huge file and less RAM

    Hi,
    I want to sort the content of a big file. In a file each line ended by \n is one record. I want to sort the lines alphabetically.
    for eg.
    The file test.txt contains the following data
    pqr xyz \n
    abc xyz \n
    The sorted file should contain
    abc xyz \n
    pqr xyz \nand also the file size is very big around 20GB. and RAM is very less so it is not even possible to load such a huge file in memory.
    How to solve the above problem? Can anyone suggest me the good solution?
    Thanks

    Getting rid of the file in favor of a database sounds pretty good to me.Have you any clue how much time it will take to insert 20 GB into a relation database?
    I find szgy's solution sutaible for me
    but I think before merging (step 5) the data in
    separate files (compare set of two files) should be
    compared and should be written to a new file. Then
    these resultant files should be compared again tili
    it becomes a single file.you can merge all the files at once to using a heap, hence avoiding unnecessary file-writes.
    >
    The above step is required since I'm reading data
    from a file. I'll be taking the first few lines and
    sorting them and writing into new file. Here each
    file is sorted. but if you merge all the sorted files
    as it is the resultant file will not have sorted data
    since there was no comparision.
    Now I'll have to think upon sorting algorithms and
    merging of files after comparing data between two
    filesYou can email me at [email protected] to get a full working code that does all this for integers, including merging the results with help of a heap.
    For 10000000 (400 MB) it takes (in ms):
    other     read     write sort
    2579     16655     35407     37422
    Total is 80 sek, which is fairly ok for 400 MB of data I think (5 MB/sek) including reads and writes.
    Gil

  • File Content Conversion in Sender File Adapter

    Hi,
    I am implementing a scenario, where I need to do Content conversion in My file Adapter.My input file is as follows
    BGN00S-A200711281003ET4
    REF38381012
    DTP007D820071128
    N1P5P5MicrosoftFI58-0612397
    INSY18030XNAN
    REFZZZZ666666666
    DTP336D819970331
    NM1ILIL1AdamsMarkE34666666666
    PERIPIPHP770555-5555
    N31470 Georgia Club Drive
    N4StathamGA30666
    DMGD819571022MM7
    HD030HLTAE1D
    My data type is as below.
    <header>
         <BGN>
              <A></A>
              <B></B>
              <C></C>
              <D></D>
         </BGN>
         <REF>
              <A1></A1>
              <B1></B1>
              <C1></C1>
              <D1></D1>
         </REF>
         <DTP>
              <A2></A2>
              <B2></B2>
              <C2></C2>
              <D2></D2>
         </DTP>
    </header>
    <Content>
         <N1>
              <A></A>
              <B></B>
              <C></C>
              <D></D>
         </N1>
         <REFAR>
              <A1></A1>
              <B1></B1>
              <C1></C1>
              <D1></D1>
         </REFAR>
         <DMP>
              <A2></A2>
              <B2></B2>
              <C2></C2>
              <D2></D2>
         </DMP>
    </Content>
    My issue is, How do I set my parameter in Sender Comm channel for content conversion especially at record structure.
    I have provided the value as Header,1,Content,*
    But its not working.
    If I do provide like
    BGN_REC,,REF_REC,,DTP_REC,,N1_REC,,INS_REC,,NM1_REC,,PER_REC,,N3_REC,,N4_REC,,DMG_REC,,HD_REC,* then ,I am not getting above XML format. Please suggest or How can I modify my Data type which competes to configure in Channel
    Thanks
    Manmadha

    Hi All,
    I am sorry for the Jumbled Content. I dont know what happened.
    I should get the XML output as below.
    header>
         <BGN>
              <A></A>
              <B></B>
              <C></C>
              <D></D>
         </BGN>
         <REF>
              <A1></A1>
              <B1></B1>
              <C1></C1>
              <D1></D1>
         </REF>
         <DTP>
              <A2></A2>
              <B2></B2>
              <C2></C2>
              <D2></D2>
         </DTP>
    </header>
    <Content>
         <N1>
              <A></A>
              <B></B>
              <C></C>
              <D></D>
         </N1>
         <REFAR>
              <A1></A1>
              <B1></B1>
              <C1></C1>
              <D1></D1>
         </REFAR>
         <DMP>
              <A2></A2>
              <B2></B2>
              <C2></C2>
              <D2></D2>
         </DMP>
    </Content>

  • Copy contents of a txt file into a transport request

    I am implementing the steps of the 990534 note.
    The note says "Create a new transport request (transaction SE09) in the source client of your Solution Manager system. Unpack file SOLMAN40_MOPZ_TTYP_SLMO_000.zip, which is attached to this note. Copy the contents of the SOLMAN40_MOPZ_TTYP_SLMO_000.txt file into the transport request."
    can anyone tell me how can I copy the contents of a txt file into a transport request?

    Hello,
    I don't know the OSS note, but I think they mean, that you have to go into the object list of your transport (in transaction SE09), switch to change mode and insert the objects from the text file.
    I guess the text file looks like:
    R3TR PROG xyz
    R3TR TABL abc
    Best regards
    Stephan

  • To get the content of a pdf file in a particular position in text format

    I am troubling with geting the content of a pdf file in a particular position.I got the code to get the content of a pdf document as whole in text format.But i only need the content at a particular area.
    i am using PDFTextStripper class in pdfBox jar to get the content as whole.
    pls send some sample code
    pls help me
    Edited by: thomas00 on Sep 21, 2007 2:55 AM
    Edited by: thomas00 on Sep 21, 2007 3:08 AM

    pls any one reply

  • Problem on reading and writing from from a *.txt file

    I get Problem on reading and writing from from a *.txt file. The following is the read() method...
    The software said the DataInputStream is depreciated. Can anyone help me please?
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        String str = "";
        try
          in = new BufferedReader(file);
          //in = new FileInputStream(file);
          for(;;)
            str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);
      }

    Thank you for your reply. I have made some change. However, there is an incompetable type found error.
    in = new BufferedReader(new InputStreamReader(in));The following are all of the code.
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        //BufferedReader in = null;
        String str = "";
        try
          in = new BufferedReader(new InputStreamReader(in));
          //in = new FileInputStream(file);
          for(;;)
            BufferedReader Bstr = new BufferedReader(new InputStreamReader(in));
            //str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);

  • How to read the content of a text file (by character)?

    Guys,
    Good day!
    I'm back just need again your help. Is there anyone knows how to read the content of a text file not by line but by character.
    Please help me. Thank you so much in advance.
    Jojo

    http://java.sun.com/javase/6/docs/api/index.html
    package java.io
    InputStream.read(): int
    Reads the next byte of data from the input stream.
    Implementation:
    InputStreamReader
    An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

  • Help on how to read the content of an XML file from the payload

    I have a receiver channel / mail adapter, that sends e-mails with a XML attachment.
    I’m trying to write a Bean, that should make it possible to rename the attached XML file dynamically.
    In the Bean I want to read the content of the attached XML file, it could be the “order number”.
    The filename should then be “Order number”.XML.
    <u><i>Can anyone help me with how to read the content of the XML file from the payload.</i></u>
    <i><b>Frank</b></i>

    hi,
    check this: http://jakarta.apache.org/poi/

  • Unable to view the contents in NQS Config file

    Hi Forum,
    After I successfully install the OBI EE 10.1.3 Application, I am unable to view the contents in NQS Config file. It is opening in Notepad with error showing as "The filename, directory name or volume label syntax is incorrect."
    So please guide me in resolving this issue.
    Regards
    Cool j

    You probably have restricted access to the file. Check if the drive is ntfs. If the os user is in administrator group, you can give permissions in file properties.

  • Easy way to add content from a last file like a word document?

    Is there somebody who can tell me how i can display content from a word file.
    I have files with content inside on my network for example a word document.
    Inside this document i've got hyperlinks to content on other pages from the same document. Is the a way or a method how i can display the content in the portal.
    Do i need to cut and paste the word content of should i save the content as a XML or a HTML document and then add the document to portal
    Regards
    Andre

    Yeah, I have an idea... Have you tried the pdf export yet? If it is already formated then that maybe the way to go. But you may need acrobat to save it in another format. If I recall InDesign renders the pdf, which would make editing the pdf in Indesign useless.
    OK, did a quick test with PDF. Load the PDF into Acrobat and save as a word file. Place the word file into InDesign and you will have the styles paragraphs.    You just have to alter the style taste, may be fix a few paragraphs if needed.

  • How to get the content in embed swf file in Swf Loader on run time

    How to get the content in embed swf file in Swf Loader on run time
    [Bindable]
    [Embed(source="assets/index.swf")]
       private var SWFSRC:Class;
    <mx:SWFLoader id="_swfloader" source="{SWFSRC}" />

    Hi Flex harUI,
    Throw the error.
    Access of undefined property content

  • Error while writing the data into the file . can u please help in this.

    The following error i am getting while writing the data into the file.
    <bindingFault xmlns="http://schemas.oracle.com/bpel/extension">
    <part name="code">
    <code>null</code>
    </part>
    <part name="summary">
    <summary>file:/C:/oracle/OraBPELPM_1/integration/orabpel/domains/default/tmp/
    .bpel_MainDispatchProcess_1.0.jar/IntermediateOutputFile.wsdl
    [ Write_ptt::Write(Root-Element) ] - WSIF JCA Execute of operation
    'Write' failed due to: Error in opening
    file for writing. Cannot open file:
    C:\oracle\OraBPELPM_1\integration\jdev\jdev\mywork\
    BPEL_Import_with_Dynamic_Transformation\WORKDIRS\SampleImportProcess1\input for writing. ;
    nested exception is: ORABPEL-11058 Error in opening file for writing.
    Cannot open file: C:\oracle\OraBPELPM_1\integration\jdev\jdev\mywork\
    BPEL_Import_with_Dynamic_Transformation
    \WORKDIRS\SampleImportProcess1\input for writing. Please ensure 1.
    Specified output Dir has write permission 2.
    Output filename has not exceeded the max chararters allowed by the
    OS and 3. Local File System has enough space
    .</summary>
    </part>
    <part name="detail">
    <detail>null</detail>
    </part>
    </bindingFault>

    Hi there,
    Have you verified the suggestions in the error message?
    Cannot open file: C:\oracle\OraBPELPM_1\integration\jdev\jdev\mywork\BPEL_Import_with_Dynamic_Transformation\WORKDIRS\SampleImportProcess1\input for writing.
    Please ensure
    1. Specified output Dir has write permission
    2. Output filename has not exceeded the max chararters allowed by the OS and
    3. Local File System has enough space
    I am also curious why you are writing to a directory with the name "..\SampleImportProcess1\input" ?

  • To view the flash technology content in this pdf file please install this version of flash player

    I am getting an error while opening a pdf file I am using Windows 7 with adobe 10.1.7 installed error message " to view the flash technology content in this pdf file please install this version of flash player"

    Both ActiveX and plugin?  What versions?

Maybe you are looking for

  • The Problem is Solved

    My problem is that when during a new windows 2000 installation, windows can`t find the Sata-disk.   I have followed the instructions in the quick user guide, but that doesnt work at all. I have tried installing all the drivers for the sata controller

  • How to store data in JavaCard

    Hi folks, I have a basic question. I want to store data in Java card of each transaction in a log file. Each record contains some information. I'm wondering how to create this kind of file on java card and update log file for each new transaction. Su

  • Message "Battery Not Installed" when it is

    When I run RAID Admin, it shows that the left battery is not installed. However, the green light is on in that battery. Any idea why that would be? I would greatly appreciate any assistance. Thanks, Joel Message was edited by: fire_wired

  • HT1727 how do i register my new pc so it can transfer use my itunes songs I already paid for that are currently on my ipad2

    i have bought songs from  itunes they are currently on my ipad2 i want to play them on my new pc cant figure out how to do it

  • Top of page data is repeated while going back from alv report

    Hi,    In my alv report , I call ed TOP_OF_PAGE.   Data regatding top_of_page is stored in internal table.    After executing the report,while going back from report,  a screen containing top_of_page data is appeaing.    Even though I cleared that ta