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;
}
文件输入是->哈哈哈;密码; 我使用分隔符将行分成两个标记,即“哈哈哈”和“密码”。我的问题是,如果 .txt 文件中有更多行,如何将我的用户名和密码映射到 HashMap 中,并且我的密码对应于我的用户名。
最佳答案
其中大部分内容也已由之前的答案完成。
我建议尽可能使用 LinkedHashMap 来保持输入顺序,并使用 Reader 作为 API 参数,以避免在文件不够时重复代码。
并且 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/