簡體   English   中英

映射字符串數組

[英]Mapping a string arrays

    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中,而我的密碼對應於我的用戶名。

而緩沖的閱讀器有更多行:

while ((line = br.readLine()) != null) {
   // process the line.
}

您需要在這里循環:

while ((s = br.readLine()) != null) {
   String[] split = s.split(";");
   for (int j = 0; j < split.length; j++) { 
    m.put(split[j], split[(j += 1)]);
  }
}

您可以嘗試以下方法:

BufferedReader br = new BufferedReader(fr);

String s = br.readLine();
while( s != null) {
    String[] split = s.split(";");
    m.put(split[0], split[1]);
    s = br.readLine();
}
br.close();

我強烈建議使用IOUtils進行文件操作...

多數情況也是通過先前的答案完成的。

我建議盡可能使用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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM