FileReader + HashTable

Hi,
This is my problem : I have a text file like this :
param.ini
[Keys]
mol2
sdf
smi
[Keys]
#comment
[mol2_to_sdf]
dbtranslate input.mol2 output.sdf
[smi_to_mol2]
dbtranslate imput.smi output.mol2
[End]
And I want to read this file to store some datas in a HashTable like that :
Key1 --> mol2
Key2 --> sdf
Key3 --> smi
mol2_to_sdf --> dbtranslate input.mol2 output.sdf
smi_to_mol2 --> dbtranslate imput.smi output.mol2
And I want to write a code like that
BufferedReader br;
FileReader fr;
String line;
try {
        FileReader fr = new FileReader("param.ini");
        br = new BufferedReader(fr);
        Hashtable hash = new Hashtable();
        while (!(line = br.readLine()).equals("[End]")) {
            if (line.startsWith("#") || (line.equals("\n"))) {
            else if (line.equals("[Keys]")) {
                    do {
                        hash.put("Keys" + i,line.next());
                        i++;
                    } while (!line.equals("[/Keys]"));
        }but the problem is that I do not find a method like "line.next()"...
So the question is : how to write a code that permits to put the line after the one that is beeing read by readline in the HashTable ?

I suggest:
else if (line.equals("[Keys]")) {
line = br.readLine();
while( !line.equals("[Keys]") ){
hash.put("Keys" + i,line);
i++;
line = br.readLine();
..................

Similar Messages

  • Hashtables and Objects, ugly.

    Let's see...
    I'll give you everything, then highlight problems.
    package Analyze;
    import java.io.*;
    import java.util.*;
    public class Work {
        public static int Operate(String directory, String filename, String directory2, String filename2, String ext, int number) {
            int sum=0;
            try{
                BufferedWriter out = new BufferedWriter(new FileWriter(directory+filename));
                BufferedReader in = new BufferedReader(new FileReader(directory2+filename2+ext));
                String str;
                int b;
                int w;
                int low=10000;
                int high=0;
                int count=0;
                Hashtable table=new Hashtable();
                while ((str = in.readLine()) != null) {
                    if  ((w=str.indexOf("Total Run Time"))>0)
                    {w=str.indexOf("Total Run Time");
                     String substr=str.substring(0, w-1);
                     String change="<TH>";
                     String newString=Replace.replace(str,substr,change);
                     int z=newString.indexOf(":");
                     String substr2=newString.substring(0, z+2);
                     String change2="";
                     String finalString=Replace.replace(newString, substr2, change2);
                     int i = Integer.parseInt(finalString);
                     int q=1;
                     if (table.get(new Integer(i))==null)
                        {table.put(new Integer(i),new Integer(q));}
                     if (table.get(new Integer(i))!=null)
                        {int v=Integer.parseInt(table.put(new Integer(i),new Integer(q)));
                         v=v+q;
                         table.put(new Integer(i), new Integer(v));
                     if (i>high)
                         high=i;
                     if (i<low)
                         low=i;
                     sum+=i;
                     count++;
                BufferedWriter instances = new BufferedWriter(new FileWriter("C:\\development\\test\\test_Local\\archives\\number"+Date.whatMonth()+Date.whatDay()+Date.whatYear()+"test"+number+".txt"));
                for (int n=0; n<=high; n++)
                    { if (table.get(new Integer(n))!=null)
                      {instances.write(table.get(new Integer(n))+" threads took "+n+" seconds.");
                        instances.flush();}
                instances.close();
                String strSum=""+sum;
                String strLow=""+low;
                String strHigh=""+high;
                double average=(double)sum/count;
                String strAverage=""+average;
                String strCount=""+count;
                out.write("<HTML> <BODY>");
                out.write("<P>These are the results of the stress test conducted for: "+Date.whatMonth()+"-"+Date.whatDay()+"-"+Date.whatYear()+"<P>");
                out.write("<BR><I>Total number of users ----- </I>"+strCount+" <B>(Note: This number is number of users multiplied by number of cycles.)</B>");
                out.write("<P><B>Time to complete in seconds: </B>"+strSum);
                out.write("<BR><B>The quickest thread took</B> "+strLow+" <B>seconds.</B>");
                out.write("<BR><B>The longest thread took</B> "+strHigh+" <B>seconds.</B>");
                out.write("<BR><B>The average is </B>"+strAverage+" <B>seconds.</B>");
                out.write("<P><P>The corresponding log file is: <a href=archives/"+filename2+Date.whatMonth()+Date.whatDay()+Date.whatYear()+".txt> Located in the archives bin. </A>");
                out.write("<P><P>The list of times and their instances is located :<a href=archives/number"+Date.whatMonth()+Date.whatDay()+Date.whatYear()+"test"+number+".txt> here </A>");
                NewFile.MakeFile(directory, "testlist.html");
                BufferedWriter lister = new BufferedWriter(new FileWriter(directory+"testlist.html", true));
                String strNum=""+number;
                lister.write("<a href="+filename+">Results from: "+Date.whatMonth()+"-"+Date.whatDay()+"-"+Date.whatYear()+"(Test number: "+strNum+")</A><P>");
                lister.close();
               /* File file=new File(directory+filename2);
                int compare=1;
                if (file.exists())
                {BufferedReader text = new BufferedReader(new FileReader(file));
                 String stuff;
                 if( (stuff=text.readLine())!=null)
                     compare=Integer.parseInt(stuff);
                 text.close();
                float second=((compare/sum)-1)*100;
                int benchmark=1500;
                float third=((benchmark/sum)-1)*100;
                String strThird;
                String strSecond;
                if (second < 0)
                    strSecond="<font color=red>"+second+"% </font>";
                else strSecond=""+second+"% ";
                if (third < 0)
                    strThird="<font color=red>"+third+"% </font>";
                else strThird=""+third+"% ";
                out.write("<BR><B>Compared to yesterday, there has been a </B>"+strSecond+"<B>change</B> (Note: Positive values shows the processes being done faster. Negative values demonstrate a dropoff in performance.)");
                out.write("<BR><B>Compared to the benchmark, there has been a </B>"+strThird+"<B>change</B> (Note: Positive values shows the processes being done faster. Negative values demonstrate a dropoff in performance.)");*/
                out.write("</BODY></HTML>");
                in.close();
                out.close();
                /* BufferedWriter cout = new BufferedWriter(new FileWriter("C:\\development\\test\\test_Local\\archive"+Date.whatMonth()+Date.whatDay()+".txt"));
                cout.write(strSum);
                cout.close(); */
               File fil = new File(directory2, filename2+ext);
                if (fil.exists()==false)
                    System.out.println("File doesn't exist!");
                File archive = new File("C:\\development\\test\\test_Local\\archives\\");
                if (archive.exists()==false)
                {archive.mkdir();
               /* File other=new File("C:\\development\\test\\test_Local\\archives\\"+filename2+Date.whatMonth()+Date.whatDay()+Date.whatYear()+".txt");
                boolean success= fil.renameTo(new File(archive, other.getName()));
                if(!success)
                {System.out.println("Could not move file");*/
            catch (IOException e)
            {System.out.println(e);}
            number++;
            return number;
    }Now, I don't really understand hashtables, so this may be completely wrong. However, here's the goal:
    I'm taking in a ton of ints, ranging from 1 to infinity. I want to create a hashtable which has the integer as the key, and the number of times it has come up as its value. Now, if an integer comes up more than once, I need to increase the value, I can't just throw it out. However, the hashtable keeps telling me that if I'm getting the value from a key I select and trying to put it into a new int, I'm an idiot because the value is of type Object. Now, how are objects going in, and not ints? Is my compiler just being crazy, or is it me?
    Also, is it necessary to create new Integers everytime I use a method from the hashtable? I haven't gotten past the compiling stage, so I don't know how the execution will go...
    Please note, everything except for the hashtable works. I have a classes that handle almost everything else, so Date.whatMonth() is really a valid command ;) Everything that's commented out is because I haven't completed the feature. Don't worry about that stuff.

    Okay, let's start with the return type.
    Hashtable.get(key) returns a value of type Object, as I'm sure you've noticed. It does this because that's as much as it can guarantee about the returned data; it could be any kind of Object, depending on what you put in. Java, however, remembers what kind of Object it is and stores its type internally.
    Thus...
    Object o = new Integer(1);
    System.out.println(o.intValue());...is illegal. Object.intValue() doesn't exist, and that's what you're asking it to do. However...
    Object o = new Integer(1);
    System.out.println(o.hashCode()); // legal because Object.hashCode() exists
    System.out.println( ((Integer)o).intValue() ); // legal because the Object was constructed as an Integer
    System.out.println( ((Short)o).shortValue() ); // throws a ClassCastException because the Object was not constructed as a ShortThus, all you need to do is recast the return value of Hashtable.get(Object) to the type that you know it should be. For example,
    Integer integer = (Integer)(my_hashtable.get(key_that_maps_to_integer));...is legal.
    Now, as for creating Integers every time... well, you probably shouldn't. I would recommend creating the following class to use as the value and the key. Note, however, that any object you create that is used as the key in a Hashtable should probably override the equals(Object) and hashCode() methods of Object.
    public class MutableInteger
        protected int m_value;
        public MutableInteger(int base)
            m_value = base;
        public int getValue()
            return m_value;
        public void setValue(int new_value)
            m_value = new_value;
        public int hashCode()
            // This must be done or all of the keys will map to the same hash code.  That would reduce the performance of the Hashtable to a linked list!
            return m_value;
        public boolean equals(Object o)
            // This must be done because, without it, no two MutableIntegers will be considered the same.
            if (o instanceof MutableInteger)
                // If the other MutableInteger has the same internal value, consider it legal.
                return (  ((MutableInteger)o).getValue() == m_value );  // Note the use of casting here.  instanceof has guaranteed that this cast is legal.
            } else
                // If the Object isn't a MutableInteger, it can't be equal to this one.
                return false;
    }Now, your code would read...
    MutableInteger key_object = new MutableInteger(0);   // Use as the key
    MutableInteger value_object = null;
    Hashtable table=new Hashtable();
    while ((str = in.readLine()) != null) {
        if ((w=str.indexOf("Total Run Time"))>0) {
            w=str.indexOf("Total Run Time");
            String substr=str.substring(0, w-1);
            String change="<TH>";
            String newString=Replace.replace(str,substr,change);
            int z=newString.indexOf(":");
            String substr2=newString.substring(0, z+2);
            String change2="";
            String finalString=Replace.replace(newString, substr2, change2);
            int i = Integer.parseInt(finalString);
            int q=1;
    /*new*/ key_object.setValue(i);
    /*dif*/ if (table.get(key_object)==null) {
    /*dif*/     table.put(key_object,new MutableInteger(q))  // Created as a MutableInteger.  The Hashtable won't remember, but the JVM will.
    /*new*/     key_object = new MutableInteger(0);  // Because the old one now belongs to the table.
    /*dif*/ if (table.get(key_object)!=null) {  // Won't this always be true?  You just put a value in there.
            // Am I correct in understanding that this code is designed to increase the value stored in the table by "q"?  If so, use the following code.
    /*new*/     value_object = (MutableInteger)(table.get(key_object));  // Note the cast.  We know that the Object returned was constructed as a MutableInteger; after all, we put it there.
    /*new*/     value_object.setValue(value_object.getValue()+1);
    /*new*/     table.put(key_object,value_object);
            if (i>high) high=i;
            if (i<low) low=i;
            sum+=i;
            count++;
    }Good luck, and have fun! ;)

  • Unexpected result in efficieny comparson of Hashtable and ArrarList

    i have been told that Hashtable is much more efficient than ArrayList. To convince my self I did the follwing:
    a) created a file of 100000 random 3 letter strings from acii range of 65 to 122. Foll. is the code I used.
    import java.util.Random;
    import java.io.*;
    class RandomStrToFile {
         public static void main(String[] args) {
              Random rnd = new Random();
              long i,imax=100000;
              char cNL;
              String sFileName = "myrandom_strings.txt";
              String sBuffer="";
              try {
              FileWriter fw = new FileWriter(sFileName);
              BufferedWriter bw = new BufferedWriter(fw);
              for (i=0; i<imax;i++){
                   sBuffer=""+ (char) (65 + (int)((rnd.nextDouble())*57)) + (char) (65 + (int)((rnd.nextDouble())*57)) + (char) (65 + (int)((rnd.nextDouble())*57));
                   bw.write(sBuffer);
                   bw.newLine();
                   //System.out.println(sBuffer);
              bw.close();
              fw.close();
              } catch (IOException e) {}
    b. Timed to create a unique valielist from the above file, uing ArrayList and Hashtable respectively. Following is my code:
    import java.io.*;
    import java.util.*;
    public class test2 {
         public static void main(String[] args){
              String sLine;
              int iVal;
              long startTime, endTime;
              ArrayList<String> al = new ArrayList<String>();
              Hashtable ht = new Hashtable (4999); // use a prime number
              try {
                   FileReader fr = new FileReader("C:\\Home\\MyJava\\eclipse_proj\\MyFirst\\bin\\myrandom_strings.txt");
                   BufferedReader br = new BufferedReader(fr);
                   startTime = System.currentTimeMillis();
                   iVal=0;
                   while ((sLine=br.readLine())!=null){
                        //System.out.println(sLine);
                        iVal=iVal+1;
                        if (!ht.contains(sLine)){
                             ht.put(iVal,sLine);
                             //System.out.println(sLine);
                   endTime = System.currentTimeMillis();
                   System.out.println("The Hashtable Elapsed Time is: " + (startTime-endTime));
                   br.close();
                   fr.close();
                   fr = new FileReader("C:\\Home\\MyJava\\eclipse_proj\\MyFirst\\bin\\myrandom_strings.txt");
                   br = new BufferedReader(fr);
                   startTime = System.currentTimeMillis();
                   iVal=0;
                   while ((sLine=br.readLine())!=null){
                        //System.out.println(sLine);
                        iVal=iVal+1;
                        if (!al.contains(sLine)){
                             al.add(sLine);
                             //System.out.println(sLine);
                   endTime = System.currentTimeMillis();
                   System.out.println("The ArrayList Elapsed Time is: " + (endTime-startTime));
                   br.close();
                   fr.close();
              } catch (IOException e){}
    To my surprize Hashtable approach was much slower thatn the ArrayList approach. Am I missing something here?

    ////////////////////////////////////////datafile creation code///////////////////////////////
    import java.util.Random;
    import java.io.*;
    class RandomStrToFile {
         public static void main(String[] args) {
              Random rnd = new Random();
              long i,imax=100000;
              char cNL;
              String sFileName = "myrandom_strings.txt";
              String sBuffer="";
              try {
              FileWriter fw = new FileWriter(sFileName);
              BufferedWriter bw = new BufferedWriter(fw);
              for (i=0; i<imax;i++){
                   sBuffer=""+ (char) (65 + (int)((rnd.nextDouble())*57)) + (char) (65 + (int)((rnd.nextDouble())*57)) + (char) (65 + (int)((rnd.nextDouble())*57));
                   bw.write(sBuffer);
                   bw.newLine();
                   //System.out.println(sBuffer);
              bw.close();
              fw.close();
              } catch (IOException e) {}
    }////////////////////////////////Testing code//////////////////////////////////
    import java.io.*;
    import java.util.*;
    public class test2 {
         public static void main(String[] args){
              String sLine;
              int iVal;
              long startTime, endTime;
              ArrayList<String> al = new ArrayList<String>();
              Hashtable ht = new  Hashtable (4999); // use a prime number
              try {
                   FileReader fr = new FileReader("C:\\Home\\MyJava\\eclipse_proj\\MyFirst\\bin\\myrandom_strings.txt");
                   BufferedReader br = new BufferedReader(fr);
                   startTime = System.currentTimeMillis();
                   iVal=0;
                   while ((sLine=br.readLine())!=null){
                        //System.out.println(sLine);
                        iVal=iVal+1;
                        if (!ht.contains(sLine)){
                             ht.put(iVal,sLine);
                             //System.out.println(sLine);
                   endTime = System.currentTimeMillis();
                   System.out.println("The Hashtable Elapsed Time is: " + (startTime-endTime));
                   br.close();
                   fr.close();
                   fr = new FileReader("C:\\Home\\MyJava\\eclipse_proj\\MyFirst\\bin\\myrandom_strings.txt");
                   br = new BufferedReader(fr);
                   startTime = System.currentTimeMillis();
                   iVal=0;
                   while ((sLine=br.readLine())!=null){
                        //System.out.println(sLine);
                        iVal=iVal+1;
                        if (!al.contains(sLine)){
                             al.add(sLine);
                             //System.out.println(sLine);
                   endTime = System.currentTimeMillis();
                   System.out.println("The ArrayList Elapsed Time is: " + (endTime-startTime));
                   br.close();
                   fr.close();
              } catch (IOException e){}
    }OK here we go. I cannot get rid of the file as taht is where I put the strings. See wheter you can find the issue.

  • Help with program using hashtable to count words & other chars in txt file

    I need to use only a hashtable to count the occurences words and chars in a text file and display them alphabetically. I am not to use anything but the hashtable. so far, I can get it to count only the words in the file and not the chars, I want to know how to make it count the chars (,.;:?(){}[]!@#$%^&\t\"<>/`~ ) that may be found and if it is possible to get it to display them in a sorted (alphabetical) order w/o using anything else.
    This is what I have: mport java.io.*;
    import java.util.*;
    import javax.swing.JOptionPane;
    class words{
    String word;
    int count;
    public class WordCount{
    static Hashtable h=new Hashtable();
    static words w;
    static void countWords(String s){
    if((w=(words)h.get((java.lang.Object)s))==null){
    w=new words();
    w.word=s;
    w.count=1;
    h.put(s,w);
    }else{
    w.count++;
    h.remove(s);
    h.put(s,w);
    public static void main(String args[]){
    String s;
    StringTokenizer st;
    String t;
    String fn = JOptionPane.showInputDialog("Enter the filename:");
    BufferedReader br = null;
    try{
    br = new BufferedReader(new FileReader(fn));
    s=br.readLine();
    while(s!=null){
    st= new StringTokenizer(s, " ,.;:?(){}[]!@#$%^&\t\"<>/`~  ");
    // Split your words.
    while(st.hasMoreTokens()){
    t=st.nextToken();
    countWords(t);
    s=br.readLine();
    }catch(Exception e){
    e.printStackTrace();
    Enumeration e=h.elements();
    w=(words)e.nextElement();
    while(e.hasMoreElements()){
    System.out.println(w.word + " " + w.count);
    w=(words)e.nextElement();
    System.exit(0);
    }

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

  • NEED HELP WITH WORD & CHAR COUNT USING HASHTABLE

    I have to use a hashtable to be able to count all the words and characters (#'s, punctuations, etc) from a file
    I have been able to get it to correctly count the words in the file but none of the characters and it also does not display the words alphabetically and just displays it in an odd way
    Here's the code: public static void main (String [] args)
          Hashtable table = new Hashtable();
          String input = JOptionPane.showInputDialog("Enter the filename:");
          try{
          BufferedReader br = new BufferedReader(new FileReader(input));
          String s = br.readLine();
          StringTokenizer words = new StringTokenizer( s, " \n\t\r" );
            while ( words.hasMoreTokens() ) {
             String word = words.nextToken().toLowerCase(); // get word
             // if the table contains the word
             if ( table.containsKey( word ) ) {
                Integer count = (Integer) table.get( word ); // get value
                // and increment it
                table.put( word, new Integer( count.intValue() + 1 ) );
             else // otherwise add the word with a value of 1
                table.put( word, new Integer( 1 ) );
           } // end while
             String output = "";
          Enumeration keys = table.keys();
          // iterate through the keys
          while ( keys.hasMoreElements() ) {
             Object currentKey = keys.nextElement();
             output += currentKey + "\t" + table.get( currentKey ) + "\n";
             System.out.println(output.toString());
          catch (IOException e)
            System.out.println(e);
          }The output that I get for a file containing the line " Hi this is my java program" is:
    this     1
    this     1
    program     1
    this     1
    program     1
    hi     1
    this     1
    program     1
    hi     1
    java     1
    this     1
    program     1
    hi     1
    java     1
    is     1
    this     1
    program     1
    hi     1
    java     1
    is     1
    my     1
    I'm not sure what I am doing wrong and help would be greatly appreciated.

    I have been able to get it to correctly count the
    words in the file but none of the characters and it
    also does not display the words alphabetically and
    just displays it in an odd way
    That's because hash tables are not ordered; to maintain order of insertion you could use LinkedHashMap and to maintain alphabetical order TreeMap.

  • How can i get the all values from the Property file to Hashtable?

    how can i get the all values from the Property file to Hashtable?
    ok,consider my property file name is pro.PROPERTIES
    and it contain
    8326=sun developer
    4306=sun java developer
    3943=java developer
    how can i get the all keys & values from the pro.PROPERTIES to hashtable
    plz help guys..............

    The Properties class is already a subclass of Hashtable. So if you have a Properties object, you already have a Hashtable. So all you need to do is the first part of that:Properties props = new Properties();
    InputStream is = new FileInputStream("tivoli.properties");
    props.load(is);

  • Unable to reference items in a hashtable

    HI,
    I'm having a bad PowerShell day today!
    My sample script to read in a text file and put the data into a hash table works just fine:
    $InputFile=Get-Content C:\Out\ktf06011.REQ
    $CurrentUserHashTable = @{}
    ForEach ($Line in $InputFile)
    $Data=$Line.Split("=")
    $Label=$Data[0].Trim()
    $Label=$Label.Insert(($Label.Length),"`"")
    $Label=$Label.Insert(0,"`"")
    $Value=$Data[1].Trim()
    $Value=$Value.Insert(($Value.Length),"`"")
    $Value=$Value.Insert(0,"`"")
    $CurrentUserHashTable.Add($Label,$Value)
    $CurrentUserHashTable 
    However, when I use this within a script that uses a file system watcher event to discover the presence of the text file, I cannot get anything from the hash table. I can see my variables being created, ready to pass on to the .add statement. I have found
    a workaround for now - not using a hash table - but would love to know why I see this behaviour and suggestions for getting at the data.
    Here is the code that I'm having trouble with.
    $folder = 'c:\In'
    $OutFolder = 'c:\Out'
    $filter = '*.*'
    $CurrentUserHashTable = $NULL
    $FileSystemWatcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
    Register-ObjectEvent $FileSystemWatcher Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $InputFile=Get-Content $folder\$name
    ForEach ($Line in $InputFile)
    #Write-Host $Line
    $CurrentUserHashTable = @{}
    $Data=$Line.Split("=")
    #Write-Host "Data: " $Data
    $Label=$Data[0].Trim()
    $Label=$Label.Insert(($Label.Length),"`"")
    $Label=$Label.Insert(0,"`"")
    #Write-Host "Label: " $Label
    $Value=$Data[1].Trim()
    $Value=$Value.Insert(($Value.Length),"`"")
    $Value=$Value.Insert(0,"`"")
    #Write-Host "Value: " $Value
    $CurrentUserHashTable.Add($Label,$Value)
    $CurrentUserHashTable
    Move-Item $folder\$name $OutFolder -Force
    #Label: "ID"
    #Value: "abc00001"
    #Label: "PID"
    #Value: "00001"
    #Label: "Title"
    #Value: "Mr"
    #Label: "Initials"
    #Value: "XY"
    #Label: "Forename"
    #Value: "Mickey"
    #Label: "Surname"
    #Value: "Mouse"
    #Label: "Siteabbrev"
    #Value: "UK"
    #Label: "Status"
    #Value: "STAFF"
    #Label: "BUabbrev"
    #Value: "NOBU"
    #Label: "Department"
    #Value: "Finance"
    Note the commented bits at the bottom are the output of
    Write-Host "Value: " $Value
     and
    Write-Host "Label: " $Label
    Also, if the following are placed within the loop, I see all data items being returned, so I know that they are added to the hash table. If they are added outside the loop, I just get the final entry "Department"
    Write-Host "Keys:" $CurrentUserHashTable.Keys
    Write-Host "Values:" $CurrentUserHashTable.Values
    Many thanks,
    Jon

    Rhys,
    Thanks that was so obvious, I couldn't see it!
    I knew the answer would be simple.
    Made the amendment to my script and can now get at the data in the hashtable, via (e.g.)
    $Department=$CurrentUserHashTable.'"Department"'
    Thanks again.
    Jon

  • Difference Between HashMap and HashTable

    Difference Between HashMap and HashTable
    Please explain with an example

    I have a situation in Java Collection and i am not
    able to figure a good solution. I am scared about the
    performance and memory that wil be used
    I have 5 List objects with thousands and thousands of
    records in it. The List is populated by a database
    query using jdbcTemplate which return like 200,000
    records
    Each record is identified by POLICY_ID. They may be
    List with multiple records for a POLICY_ID
    I want to extract each POLICY_ID from all the 5 List
    and make a single List object for each POLICY_ID and
    for each List and pass it to a print job which will
    print the data for a POLICY_ID
    Example
    Let say we have POLICY_ID = 15432
    List1 has one record for 15432
    List2 has one record for 15432
    List3 has one record for 15432
    List4 has three record for 15432
    List5 has three record for 15432
    From the 200,000 records in List1 i want to generate
    a seperate list with 1 record for policy id 15432 and
    let name is Listperpolicy
    after this logic we have
    Listperpolicy1
    Listperpolicy2
    Listperpolicy3
    Listperpolicy4
    Listperpolicy5
    call print job ( Listperpolicy1, Listperpolicy2,
    Listperpolicy3, Listperpolicy4, Listperpolicy5)
    Please let me know
    Thanks a Lotttttttttdon't worry about performance until you've got a working application. second-guessing what the performance bottlenecks will be is futile

  • FileReader and StringTokenizer

    what I'm trying to do is to read String and Double date in a txt document here my code:
    import java.io.*;
    import java.util.*;
    public class partie1 {
         static final int limite_colones=10;
         static final int limite_lignes=10;
         static final int limite_matieres=5;
         static final int limite_eleves=15;
         static final String titre="�cole secondaire Cartierville";
         static String nomEleve[]=new String[limite_eleves];
         static double notesEleve[][]=new double[limite_eleves][limite_matieres];
         public static void main(String[] args)throws IOException {
              String ligne,ficEleve="c:/ficEleves.txt";
              BufferedReader ficnomlogique=new BufferedReader(new FileReader(new File(ficEleve)));
              while ((ligne=ficnomlogique.readLine())!=null){
                   StringTokenizer ligneTemp=new StringTokenizer (ligne,":");
                   for(int i=0;i<15;i++){
                        nomEleve=ligneTemp.nextToken();
                        System.out.println(nomEleve[i]);
                        for(int j=0;j<5;j++){
                             notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
                             System.out.println(notesEleve[i][j]);
    and this is what they give me as error message:
    Alain
    100.0
    90.0
    88.0
    60.0
    65.0
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknow Source)
    at partiel.main(partie1.java:20)
    so i understand that it doesnt change ligne or doesnt do the for correctly but i can't figure where is my mistake.
    thank for your help

    What do the records in the file look like?
    This code:
    for(int i=0;i<15;i++){
        nomEleve=ligneTemp.nextToken();
    System.out.println(nomEleve[i]);
    for(int j=0;j<5;j++){
    notesEleve[i][j]=Double.parseDouble(ligneTemp.nextToken());
    System.out.println(notesEleve[i][j]);
    will call nextToken() on each line 15 + (15 * 5) = 90 times.
    Does each line contain 90 tokens?

  • How can I get the total "values" in a hashtable ?

    i know that i can get the total values in a hashtable by hash.elements() method. It returns an
    enumeration with all the values present in this hashtable. this is fine upto here.
    Now the preoblem is:
    According to what rule this enumeration will be returned. I mean..
    If i added in key A with value a,
    then key B with value b;
    then key C with value c;
    then key D with value d;
    (They all are objects of type String)
    now i call ... hash.elements(); Suppose it returns Enumeration enum;.
    Now in what order they all are present in this hashtable.
    Meaning is that if i move arond this enum in what sequence they all will be returned.
    option A ) In the same order as they were inserted in hashtable.
    option B ) According to LIFO;
    option C) There is no fix rules , simply it return all the elements and u cannot judge that the first element in enum was really the first element inserted in the hashtable and the second element of enum was really the second element inserted in the hashtable.
    What do u think..which option is correct ?
    Ny idea will highly appreciated.
    Thanks in advance.
    Sanjeev Dhiman

    hi, i am again..
    boss ! this is not true..u just change the order and or change the keys and something like ...
    "Sanjeev", "hello"
    "Dhiman", "hi"
    "Technosys" ,"Services"
    u will find that its not LIFO..really i was thinking before coding my project that option A is correct and with knowledge i wrote 3 - 4 classes but when i run the programm its starts throwing errors.
    so, i posted this question. I think "apppu" is right.
    I think , firstly hash is calculated for each value and that value is returned which can be received in a fastest way and hence not necessarily in LIFO and FIFO..
    Thanks to u also as u gave ur precious time for me.
    Once again.
    Thank you very much.
    Sanjeev Dhiman

  • Problem in Jtree while retrieving values from a hashtable

    Hi
    I am trying to show some values in a Jtree.I am receiving the values in a hashtable.The hashtable contains unique key but duplicate values.i want to show that values of that hashtable in a tree(but unique values)and under each value show all the key of it.can you please tell me how to do that.
    thanks

    If i understand right, you want to do something like this:
                   Hashtable values = yourhashtable;        
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("Values");
              HashMap<Object, DefaultMutableTreeNode> nodes = new HashMap<Object, DefaultMutableTreeNode>();
              Iterator ii = values.keySet().iterator();
              while (ii.hasNext()) {
                   Object key = ii.next();
                   Object value = values.get(key);
                   if (nodes.containsKey(value)) {
                        DefaultMutableTreeNode node = nodes.get(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                   } else {
                        DefaultMutableTreeNode node = new DefaultMutableTreeNode(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                        nodes.put(value, node);
                        root.add(node);
              JTree tree = new JTree(root);Hope this helps,
    Alex.

  • Reading Values from a Hashtable.Please guideu

    Chaps,
    I am in a strange situation
    I am having a hashtable with the flwg values
    Entertainment Games
    Entertainment Video
    PIM Calculator
    Entertainment Jump
    Settings Set
    Entertainment Poker
    Now,I need to search this hashtable for the
    Object 'Entertainment' and whatever is the
    value of this,is put in an Array
    for this I am using:
    String s[];
    Enumeration e;
    for(int i=0; i<ht.size(); i++){
    String s = (String)ht.get("Entertainment");
    // I am stuck after this? Can some one please help?       
             

    Object value = ht.get("Entertainment");
    But if you are doing this (I can't tell if this is what you're doing from your first post, though):
    ht.put("Entertainment", onething);
    ht.put("Entertainment", anotherthing);
    ht.put("Entertainment", athirdthing);
    Then there will only be athirdthing in the table, cuz it'll overwrite the previous values.

  • Need help in using hashtable as a property of a form bean

    Hi,
    Is it possible to use a hashtable as a property of the bean.
    Well this is the problem i have
    I am using a hashtable as property and i want it to store from(/retrive into} form as ints/strings
    I have a
    JSP Page
    SampleAction --Action
    SampleForm --ActionForm
    Sample(bean)
    =============
    JSP Page
    (within the html:form tag)
    <html:text property="sample.number" />
    ====================
    struts-config links to
    SampleAction
    SampleForm
    ==============
    SampleForm
    Sample sample = new Sample();
    reset(){ ...impl...}
    validate(){.... impl.....}
    =================
    Sample.java
    private Hashtable prop = new Hashtable();
    public int getNumber()
       return ((Integer)prop.get("number")).intValue();
    public void setNumber(int number)
       prop.put("number",new Integer(number));
    ====================================
    this setup understandbly gives me a error like this
    no getter method for property sample.number
    PLEASE DO remember that i have a large number of mixed types in my form that needs to be populated into the bean and i detest using that many variables(in the bean)
    I NEED TO A KNOW A SOLN. PLEASE
    Thanx in advance
    cheers
    Ash

    Hi,
    I think the solution for your problem is
    put a form tag in your jsp page.
    name it as your form name defined in the struts-config.xml.
    in your case
    it is 'sample'.
    And make changes in the html:text tag like,
    <html:text name="sample" property="number" />
    Hope it will work.. have fun !!!

  • How to put data into a hashtable from a text file

    I need some help to put the words in a text file to a hashtable.The text file
    consist of words and the following set of punctuation marks {, . ; : } and spaces.
    thanks in advance.

    Navy_Coder wrote:
    6 zebras.But you must marry his eldest daughter as well, for that dowry.

  • Need to run a prog on 1.4 which is running on 1.5. .....using two hashtable

    hello,
    I've developed a program which is prefectly working on java 1.5.0 version.
    but when run on java1.4.0. it gives run time error in this code.
    first i'm getting error in second hashtable. put function where i'm using key as an integer.this is running on 1.5 version but have to change key as string on 1.4. but after that it is still not working properly.
    I want that when i clicked on open then it must show both file
    1. that have hdr extension
    2. that have same name as the corrseponding .hdr file but without extension.
    this program show desired result on 1.5 but on 1.4 it display only .hdr file.
    pls. help me regarding this .
    // class hdr file filter
    import java.io.File;
    import java.util.Hashtable;
    import java.util.Enumeration;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class hdrFileFilter extends FileFilter {
    private Hashtable filters = null;
    private Hashtable noextensionfilter = null;
    private String noextensionname=null;
    private String extensionname = null;
    private String description = null;
    private String fullDescription = null;
    private boolean useExtensionsInDescription = true;
    private String fname = null;
    public File noextensionarray[];
    int count=0;
    int counthdr=0;
    int i=0;     
         //all files are accepted.
    public hdrFileFilter()
         this.filters = new Hashtable();
         //Creates a file filter that accepts files with the given extension.
    public hdrFileFilter(String extension)
         this(extension,null);
         //Creates a file filter that accepts the given file type.
    public hdrFileFilter(String extension, String description)
         this();
         if(extension!=null)
         addExtension(extension);
         if(description!=null) setDescription(description);
         //Return true if this file should be shown in the directory pane,false if it shouldn't.
    public boolean accept(File f) {
         if(f != null) {
         if(f.isDirectory()) {
              return true;
         String extension = getExtension(f);
         if(extension != null && filters.get(getExtension(f)) != null)
              fname=f.getName();
              extensionname=fname.substring(0,fname.lastIndexOf('.'));
              counthdr+=1;
              return true;
         if(extension == null)
              noextensionfilter=new Hashtable(20);
              noextensionname=f.getName();          
              noextensionfilter.put(count,noextensionname);
              count=count + 1;
              if(noextensionfilter.get(count) == extensionname)
                   noextensionarray=new File[20];
                   noextensionarray=f
                   System.out.println("file:" +noextensionarray[i]);
                   i++;
                   return true;               
         return false;
         //Return the extension portion of the file's name .
    public String getExtension(File f)
              if(f != null)
                   String filename = f.getName();
                   int i = filename.lastIndexOf('.');
                   if(i>0 && i<filename.length()-1)
                        return filename.substring(i+1).toLowerCase();
              return null;
         //Adds a filetype "dot" extension to filter against.
    public void addExtension(String extension)
         if(filters == null)
         filters = new Hashtable(20);
         filters.put(extension.toLowerCase(), this);
         fullDescription = null;
    public String getDescription()
              if(fullDescription == null)
                   if(description == null || isExtensionListInDescription())
                        fullDescription = description==null ? "(" : description + " (";
                        // build the description from the extension list
                        Enumeration extensions = filters.keys();
                        if(extensions != null)
                             Object nn=extensions.nextElement();
                             fullDescription += "." + nn;     
                             while (extensions.hasMoreElements())
                                  fullDescription += ", ." + nn;
                        fullDescription += ")";
                   else
                        fullDescription = description;
              return fullDescription;
    public void setDescription(String description)
         this.description = description;
         fullDescription = null;
    public void setExtensionListInDescription(boolean b) {
         useExtensionsInDescription = b;
         fullDescription = null;
              public boolean isExtensionListInDescription()
              return useExtensionsInDescription;

    Might be fixable if you do something like
    javac -target 1.4
    Bytecodes are different in 1.5 and thus not backward compatible

Maybe you are looking for