Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Hashtable Keys not responding

Posted on 2003-03-08
5
Medium Priority
?
262 Views
Last Modified: 2010-03-31
Hi,

I cant seem to read the values from the Hashtable in this program. The programs reads a txt file that looks like this

User-Agent : HertsWeb/1.0
Accept-Language : en
Accept : text/plain
Accept : application/x-html
Accept : application/html

Everything is read into a HashTable. But i cant seem to read any value from it as it returns null, i think the problem is the value i am assigning to the key.. e.g. theDetails.get(String new("User-Agent"))
-----------------------------------------------------------------------------------------------


        public BrowserDetails()
        {
              // Initialise all valus to null
              theDetails = null;
              inStream = null;
              outStream = null;
              
              // Create the details hashtable
              theDetails = new Hashtable();
              
              
              // Get and set contents of the file
              readBrowserDetails();
        }//BrowserDetails
      
      /******************************************************************************
      * Private Methods                                                                                            *
        *******************************************************************************/
      
      // Method reads the contents of the file and stores each value no the
      // Hashtable
      
      private void readBrowserDetails()
      {
            try
            {
                  
                  // Set up the input stream for reading
                  inStream = new FileInputStream(browserFile);
                  
                  // Set up the input stream for reading one line at a time
                  fileInput = new BufferedReader(new InputStreamReader(inStream));
                  
                  // While there is something to read
                  for (i=0; (tempStorage=fileInput.readLine()) != null;i++)
                  {
                        // Create a tokenise with what was just read
                        StringTokenizer tokenizer = new StringTokenizer(tempStorage, ":");
                        
                        //Separate the string in the form string1 string2 string3
                        //We only need string1 and string3 threfore we will discards string 2
                        
                        String tempKey = new String();
                        String tempValue = new String();
                        int index = 1;
                        
                        // Get three tokens from the string
                        while (tokenizer.hasMoreTokens())
                        {
                              
                              tempKey = tokenizer.nextToken().toString();
                              tempValue = tokenizer.nextToken();
                              theDetails.put(new String(tempKey),new String(tempValue));
                        }// while has more tokens
                        
                        //Put current Element into hashtable
                        
                        
                               
                   }// for index=0
                    //theDetails.put("asdf","asdf");                  
                   System.out.println("---------- " + theDetails.get(new String("User-Agent")));
                   System.out.println("\n---------- " + theDetails.containsKey((String)("User-Agent")));
                   System.out.println("\n---------- " + theDetails.containsKey(new String("Accept")));
                   System.out.println("\n---------- " + theDetails.containsKey((String)("Accept")));
                   System.out.println("\n---------- " + theDetails.containsKey("asdf"));
                   System.out.println("\n---------- " + theDetails.contains("en"));
                   System.out.println("\nEmptry " + theDetails.isEmpty());
                   System.out.println("\nsize " + theDetails.size());
                         System.out.println("\nset " + theDetails.entrySet());
                         System.out.println("\nkeys " + theDetails.keys());

            }//try
            catch(Exception e)
            {
                  //print the error
                  e.printStackTrace();
            }
            
            //Close the streams
            try
            {
            fileInput.close();
            inStream.close();
            }
            catch(Exception e){}
      
      } //readBrowserDetails()
      
      public static void main(String args[])
      {
            BrowserDetails anObject;
            anObject = new BrowserDetails();
      }

} //Class HTTPConnection
--------------------------------------------------------------------------------------------

Here is the output that i get if i test it

---------- null

---------- false

---------- false

---------- false

---------- false

---------- false

Emptry false

size 3

set [Accept-Language = en, User-Agent = HertsWeb/1.0, Accept = application/html]


keys java.util.Hashtable$Enumerator@16f0472

C:\My Documents\Docs\Academic\BSC4\Dissertation\Code\CPD>
0
Comment
Question by:Ziggy100
4 Comments
 
LVL 92

Accepted Solution

by:
objects earned 240 total points
ID: 8095829
looks like a problem with leading/trailing spaces, try:

theDetails.put(tempKey.trim(),tempValue.trim());
0
 
LVL 2

Expert Comment

by:functionpointer
ID: 8099731
Yes, you do indeed have a problem(?) with the whitespace. The key ends ups as "Accept ", not "Accept". ( the values also have a extra leading space ).

More importantly though:
You cannot load a Hashtable with multiple objects of the same key. In your example, "Accept" will ONLY contain "application/html" when you are done.  This is because you are using the same key (Accept) and every put method replaces the previous. KEYS must be unique in Hashtables. "Accept".hashcode() = "Accept".hashcode() everytime. ;)

You could solve this by expressing this in the file with one "Accept" header which can have a value of a comma-delim list ( just like HTTP/1.1 ), or by branching on  if(tempKey.equals( "Accept" ))  and handling them one at a time.  Regardless, you cant put them all in the Hashtable with the exact same key at the same time.

Whichever. Hope this helps.  :-)

0
 

Expert Comment

by:CleanupPing
ID: 9058841
Ziggy100:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 35

Expert Comment

by:girionis
ID: 9693331
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- Points to objects

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

girionis
EE Cleanup Volunteer
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month10 days, 16 hours left to enroll

572 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question