简体   繁体   中英

Reading from file into HashMap

I'm trying to fill my HashMap with Strings from the text file (zadania.txt) . It's a simple text file in format like :

Q: question 1
A: answer for question 1
Q: question 2
A: answer for question 2 etc ...

Then I want to write it out on console and here the problem is . It runs , but doesn't write out anything. When I change the source file it works but I'm wondering why it doesn't work with that file ( file is ok, not broken , written in Pages and saved as a text file). Anyone can help ? Here's my code :

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;


public class testClass {


public static void main(String[] args) {
    // TODO Auto-generated method stub
    File file = new File("zadania.txt");
    try {
        Scanner skaner = new Scanner(file);
        HashMap<String,String> questions = new HashMap<String,String>();
        while(skaner.hasNext()){
            String question = skaner.nextLine();
            String answer = skaner.nextLine();
            questions.put(question, answer);
        }
        Iterator<String> keySetIterator = questions.keySet().iterator();
        while(keySetIterator.hasNext()){
            String key = keySetIterator.next();
            System.out.println(key + "//** " +questions.get(key));
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

If you use that path to your file File file = new File("zadania.txt"); , you need to put your file zadania.txt in the root folder of project.

Or you can create folder resources put your file there and edit path to File file = new File("resources/zadania.txt");

Your code works for me. So, as Oli Charlesworth already mentioned, you should add some output in the first loop, to check that something gets inserted. If not you seem to have an empty file named zadania.txt .


Some other hints for further java programms:

  1. Close your skaner ! If you are using Java 7 you can use the try-with-resources:

     try (Scanner skaner = new Scanner(file)){ //... } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

    Otherwise use the finally construct:

     Scanner skaner = null; try { skaner = new Scanner(file) //... } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(skaner != null) { skaner.close(); } } 

    Otherwise you may risk (in larger programms) to run out of file handles. It's best practice to close any resource you open.

  2. Class names should be written (by convention) with a leading capital letter, so in your case it would be TestClass .

  3. If you iterate over both, the key and the value of a Map use the Map.entrySet() method to get both. With large maps this is faster than iterating over the key and the call Map.get() to get the Value.

Here is another option to read your *.txt File and put it into a HashMap

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class App {

    public static void main(String[] args) {
        Map<String, String> questions = new HashMap<>();
        Scanner scanner = null;
        try {
            scanner = new Scanner(new FileInputStream(new File("zanader.txt")));
            while (scanner.hasNext()) {
                String question = scanner.nextLine();
                String answer = scanner.nextLine();
                questions.put(question, answer);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }

        // get an iterator
        Iterator<Map.Entry<String, String>> itr = questions.entrySet().iterator();
        // and go through it
        while (itr.hasNext()) {
            // get the entryset from your map
            Map.Entry<String, String> value = itr.next();
            // return only the key
            String question = value.getKey();
            System.out.println("Get answer by key: " + questions.get(question));
            System.out.println("Question: " + value.getKey() + " - Answer: " + value.getValue());
        }
    }

}

I commented the interesting parts.

Patrick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM