2013-01-02 72 views
1
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;密码; 我用分隔符将行分成两个“hahaha”和“password”标记。我的问题是如何将我的用户名和密码映射到HashMap中,如果我的.txt文件中有更多行,则我的密码与我的用户名相对应。映射一个字符串数组

+0

怎么是'Login'一个好名字读取并分析文件的方法?在*非常*最少它应该是'登录'根据命名约定。 –

+0

谢谢。应该命名为readFile。 –

+0

什么是文件内容 - >'hahaha;密码'? “哈哈哈”是你在问题中提到的用户名吗? –

回答

0

大部分情况也是以前的答案完成的。

我建议尽可能使用LinkedHashMap来保持输入顺序,并使用Reader for API params来避免在文件不够时重复代码。

而且在分割中使用的正则表达式是稍差约束(条左右的空间“;”)

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

感谢您的解决方案。 –

0

而缓冲的读者有更多的线路:

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

你会需要循环的位置:

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

你可以试试这个:

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用于文件操作...