1

我必须阅读一个文件。文件如下——

123 http://www.xyz.com

143 http://www.qqq.com

我写了下面的代码,其中我将该文件读入哈希表。

public Hashtable<String, String> readDataFromFile(String fileName) {
            try {
                FileReader fr = new FileReader(fileName);
                BufferedReader br = new BufferedReader(fr);
                String strLine = null;
                String []prop = null;
                while((strLine = br.readLine()) != null) {
                    prop = strLine.split("\t");
                    recruiters.put(prop[0], prop[1]);
                }
                br.close();
                fr.close();

            }catch(Exception exception) {
                System.out.println("Unable to read data from recruiter file: " + exception.getMessage());
            }
            return recruiters;
        }

此函数返回一个哈希表,第一个参数为 id,第二个参数为链接

现在,我想编写一个函数,我可以在其中读取哈希表并将第二个参数附加到第一个参数,该函数应该返回一个总 url 作为结果..

类似于 www.abc.com/123

这就是我开始的方式,但它对我不起作用.. Plesae 建议改进。

public String readFromHashtable(Hashtable recruiters){

            String url=null;        
            Set<String> keys = hm.keySet();
            for(String key: keys){
                //Reading value and key
                // Appending id into url and returning each of the url.
            }
            return url;

        }
4

1 回答 1

1

如果您想要两个值(键 + 值),最简单的方法 使用.entrySet().

You need to somehow collect your URLs. In your current code, you reassign the url variable every time the loop repeats, so in the end, you only return the last url.

Something like this should work:

public List<String> readFromHashtable(Hashtable recruiters){
    List<String> urls = new ArrayList<String>(recruiters.size());      
    for(Entry e : recruiters.entrySet()){
        urls.add(e.getValue() + '/' + e.getKey());
    }
    return urls;
}

Also, why are you using HashTable instead of HashMap? The main difference is that HashTable is synchronized (used for threaded applications) and HashMap is not. If you are not using threads to operate on the HashTable, you might prefer HashMap.

于 2013-08-19T06:38:57.973 回答