简体   繁体   English

从文件读入HashMap

[英]Reading from file into HashMap

I'm trying to fill my HashMap with Strings from the text file (zadania.txt) . 我正在尝试使用文本文件(zadania.txt)中的字符串填充HashMap。 It's a simple text file in format like : 这是一个简单的文本文件,格式如下:

Q: question 1 问:问题1
A: answer for question 1 答:第一个问题的答案
Q: question 2 问:问题2
A: answer for question 2 etc ... 答:回答问题2等...

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). 当我更改源文件时,它可以工作,但是我想知道为什么它不能与该文件一起工作(文件可以,没有损坏,用Pages编写并另存为文本文件)。 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"); 如果您使用该路径到文件File file = new File("zadania.txt"); , you need to put your file zadania.txt in the root folder of project. ,您需要将zadania.txt文件zadania.txt在项目的根文件夹中。

Or you can create folder resources put your file there and edit path to File file = new File("resources/zadania.txt"); 或者,您可以创建文件夹resources将文件放在此处,然后编辑File file = new File("resources/zadania.txt");路径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. 因此,正如Oli Charlesworth所述,您应该在第一个循环中添加一些输出,以检查是否插入了某些内容。 If not you seem to have an empty file named zadania.txt . 如果不是,您似乎有一个名为zadania.txt的空文件。


Some other hints for further java programms: 有关进一步的Java程序的其他一些提示:

  1. Close your skaner ! 关闭你的skaner If you are using Java 7 you can use the try-with-resources: 如果您使用的是Java 7,则可以使用try-with-resources:

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

    Otherwise use the finally construct: 否则,使用finally构造:

     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 . 类名(按惯例)应使用大写大写字母,因此在您的情况下为TestClass

  3. If you iterate over both, the key and the value of a Map use the Map.entrySet() method to get both. 如果同时迭代这两个,则Map的键和值将使用Map.entrySet()方法来获取两者。 With large maps this is faster than iterating over the key and the call Map.get() to get the Value. 对于大型地图,这比遍历键和调用Map.get()以获取Value更快。

Here is another option to read your *.txt File and put it into a HashMap 这是另一个读取* .txt文件并将其放入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 帕特里克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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