Solved

How can i save hashMap data into a txt file?

Posted on 2004-05-02
15
1,733 Views
Last Modified: 2008-03-10
Currently, this is what i have:

    PrintWriter out = new PrintWriter(new FileOutputStream("newFile.txt"));
    Set keyList = wordMap.keySet();
   
    Iterator iter = keyList.iterator();
   
    while (iter.hasNext()) {
      out.print(iter.next());
      out.println(wordMap.get(iter.next()));
    }
    out.close();

it seems to kind of work, but not alway???
wordMap is a hashmap that contain list of words and their frequency.
0
Comment
Question by:gom322
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
15 Comments
 
LVL 92

Expert Comment

by:objects
ID: 10974506
while (iter.hasNext()) {
      Object key = iter.next();
      out.print(key);
      out.println(wordMap.get(key));
    }
0
 

Author Comment

by:gom322
ID: 10974515
isnt that basically the same thing as what i have?
0
 
LVL 92

Expert Comment

by:objects
ID: 10974520
no you call next() twice each loop iteration when you should only be calling it once.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:gom322
ID: 10974521
one weird thing. i used a JFileChooser to get the file, and used a BufferedReader to read through the text file. what i've noticed was when i do bReader.readLine(), it seems to ignore the first character in that line. i dont get why its doing that.
0
 

Author Comment

by:gom322
ID: 10974541
one more weird thing. I actually did

while (iter.hasNext()) {
      Object key = iter.next();
      out.print(key);
      out.println(wordMap.get(key));
    }

before i posted question on this site, but the thing is it seems to miss the last key when priting. for example, i have a sentence:

i like big monkey and you like small monkey
haha. this is funny.

when i run the code, this is the output:

you1
aha.1
and1
like2
monkey1
big1
is1
this1
small1
1

you can notice that it misses the first character from each line, and the last word from each line. weird...
0
 
LVL 92

Expert Comment

by:objects
ID: 10974553
are you sure that the data in your map is not missing the 1st character
0
 

Author Comment

by:gom322
ID: 10974564
here's the code for my class. its really short.

SelectFile is just another class ihave for choosing txt files.

public class AnalyzeText {
 
  private File inFile;
  private FileReader fReader;
  private BufferedReader bReader;
  private HashMap wordMap;
  private static int END_OF_READER= -1;
 
  public AnalyzeText() {
    SelectFile chooser = new SelectFile();
    inFile = chooser.getFile();
    wordMap = new HashMap();
  }
 
  public void getWordFrequency() throws IOException {
    fReader = new FileReader(inFile);
    bReader = new BufferedReader(fReader);
   
    if (bReader.ready()) {
      while (bReader.read()!=END_OF_READER) {
        String tempStr = new String();
        String line = bReader.readLine();
        char[] charArray = line.toCharArray();
       
        for (int i=0; i< charArray.length; i++ ) {
          char tempChar = charArray[i];
         
          if (!Character.isSpaceChar(tempChar)) {
            tempStr+=tempChar;
          } else {
            int count=1;
            Integer frequency;
     
            if (wordMap.containsKey(tempStr)) {
              frequency=(Integer)wordMap.get(tempStr);
              count=frequency.intValue();
              count++;
            }
           
            frequency=new Integer(count);
            wordMap.put(tempStr, frequency);
            tempStr = new String();
          }        
        }
      }
    }
  }
 
  public void saveData() throws IOException{
    PrintWriter out = new PrintWriter(new FileOutputStream("newFile.txt"));
    Set keyList = wordMap.keySet();
   
    Iterator iter = keyList.iterator();
   
   while (iter.hasNext()) {
      Object key = iter.next();
      out.print(key);
      out.println(wordMap.get(key));
    }

    out.close();
  }
 
}
0
 
LVL 92

Expert Comment

by:objects
ID: 10974585
>  while (bReader.read()!=END_OF_READER) {

that line reads the first char from line and is lost.


it would be a lot easier to use a StringTokenizer to parse the words.
0
 
LVL 92

Accepted Solution

by:
objects earned 50 total points
ID: 10974594
String line = null;
while (null!=(line=in.readLine()))
{
   StringTokenizer st = new StringTokenizer(line);
   while (st.hasMoreTokens())
   {
      String word = st.nextToken();
      ...
0
 

Author Comment

by:gom322
ID: 10974598
WOuld i have to delete that line of code? if so , how would that line of code be reimplemented so that it does keep reading text even if it reached the end.
i dont see how i could make it so it doesnt read the first char.

it would be easier to use StringTokenizer, but i cant use it for this time.
0
 

Author Comment

by:gom322
ID: 10974610
okay. it got the first character but still misses the last word.. also, is there a way for the user to specify where and the file name he wants to save this as??
0
 
LVL 92

Expert Comment

by:objects
ID: 10974618
you only process a word when you find a space, so the last word doesn't get processed.
0
 

Author Comment

by:gom322
ID: 10974634
haha. okay i got it. thanks alot. one more thing, is there a way for a user to specify a directory and file name it wants to save under?
0
 
LVL 92

Expert Comment

by:objects
ID: 10974665
Use JFileChooser
0
 

Author Comment

by:gom322
ID: 10974666
oh you can use filechooser for this too. okay. thanks
0

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
login form jsp example 2 71
JAVA API design with micro service cloud in mind 1 113
hashmap order 17 63
Java List 4 76
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.
Suggested Courses

751 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