从user.txt把所有数据都读出来装到map中输出:
public static Map<String, String> getMap(){ Map<String, String> map = new HashMap<>(); try { String encoding="GBK"; File file=new File("./web/user.txt"); if(file.isFile() && file.exists()){ //判断文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file),encoding);//考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while((lineTxt = bufferedReader.readLine()) != null){ String[] s = lineTxt.split(" "); map.put(s[0],s[1]); } read.close(); }else{ System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } return map; }
public static void main(String[] args) { Map<String, String> map = User.getMap(); for(Map.Entry<String,String> m : map.entrySet()){ System.out.println("m.getKey() = " + m.getKey()); System.out.println("m.getValue() = " + m.getValue()); } }