简体   繁体   中英

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;
    }

file input is -> hahaha; password; I used a delimiter to split the line into two tokens which are "hahaha" and "password". My question is how do I map my username and password into a HashMap with my password corresponds to my username if I have more lines in my .txt file.

while the buffered reader has more lines:

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

You would need to loop here:

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

You could try this:

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();

And I strongly suggest using IOUtils for file operations...

Most of this has been done by previous answers as well.

I suggest using LinkedHashMap to keep the input order whenever possible and use Reader for API params to avoid duplicating code as soon as files are not enough.

And the regex used in split is somewhat less constraining (strips spaces around ';')

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);
        }
    }
}

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