java - 映射字符串数组

标签 java parsing map

    private Map<String, String> readFile(String file) throws IOException{
        FileReader fr = null;
        Map<String, String> m = new HashMap<String, String>();
        try {
        fr = new FileReader(file); 
        BufferedReader br = new BufferedReader(fr);

        String s = br.readLine();
        String[] split = s.split(";");
        for (int j = 0; j < split.length; j++ ) { //Just a temporary solution.
            m.put(split[j], split[(j+=1)]); //inserts username and password from file
        } 
        br.close();
        }
        catch (FileNotFoundException e){
            System.out.format("%s not found.%n", file);
            System.exit(1);
        }
        fr.close();

        return m;
    }


文件输入是-> haha​​ha;密码;
我使用了一个定界符将行分成两个标记“ haha​​ha”和“ password”。我的问题是,如果我的.txt文件中包含更多行,我该如何将我的用户名和密码映射到HashMap中,而我的密码对应于我的用户名。

最佳答案

多数情况也是通过先前的答案完成的。

我建议尽可能使用LinkedHashMap保持输入顺序,并使用Reader for API params避免文件不足时立即复制代码。

而且在split中使用的正则表达式的约束较少(在';'周围带空格)

public class ParseLogin {

    /**
     * Parses lines of username password pairs delimited by ';' and returns a Map
     * username->password.
     *
     * @param reader source to parse
     * @return Map of username->password pairs.
     * @throws IOException if the reader throws one while reading.
     */
    public static Map<String, String> parse(Reader reader) throws IOException {

        Map<String, String> result = new LinkedHashMap<String, String>();
        BufferedReader br = new BufferedReader(reader);
        String line;
        while (null != (line = br.readLine())) {
            String fields[] = line.split("\\s*;\\s*");
            if (fields.length > 1) {
                result.put(fields[0], fields[1]);
            } // else ignore (or throw Exception)
        }
        return result;
    }


    public static void main(String[] args) {

        try {
            Map<String, String> result = parse(new FileReader(args[0]));
        } catch (FileNotFoundException e) {
            System.out.format("%s not found.\n", args[0]);
            System.exit(1);
        } catch (IOException e) {
            System.out.format("Error while reading from %s.\n", args[0]);
            e.printStackTrace();
            System.exit(2);
        }
    }
}

关于java - 映射字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14124275/

相关文章:

c - 使用 MiniXML 在 C 中解析 XML 文件

linux - 使用 awk/sed/cut/grep 从文本文件中提取冒号分隔的字段/值

java - 如何使用 Dagger 2 将 idemId 注入(inject)演示者? Dagger .android

java - 在 java 中更改 bufferedImage 像素

c++ - 重载C++提取运算符>>解析数据的例子

java - 为什么 Java 在 Map 中没有 putIfAbsent(key, supplier) 方法?

c++ - 在 C++ 中执行 Map<Key, Map<Key, Set< Class>>> 是很痛苦的。有没有更好的办法?

java - 输出 Java map 并在 HTML 中混合

java - Jaxb2Marshaller 无法以线程安全的方式解码非 XmlRoot 元素

java - 在 struts2 messages.properties 中插入新行