2013-02-15 76 views
0

我有以下格式的文本文件: UserName Password 两个单独的行。 我想输入用户名到用户名字段(很明显),并只输入密码相同的密码字段。 我的测试曾经为每个元素定义了一个String元素,这一切都很好,因为我只是简单地调用String元素。问题是我无法检查我的代码,因为它有我的个人活动目录登录信息。所以我试图从文本文件中读取它。我有以下的代码来做到这一点:读取用户名和密码从文本文件

 try 
    { 
     FileInputStream fstream = new FileInputStream(".../Documents/userInfo.txt"); 
     // Use DataInputStream to read binary NOT text. 
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
     String strLine; 
     int count = 0; 
     strLine = br.readLine(); 
     count++; 

     while(strLine!= null) 
     { 
      //Enter userName 
      WebElement userName = driver.findElement(By.id("username")); 
      userName.clear(); 
      userName.sendKeys(strLine); 
      System.out.println(strLine); 

      strLine = br.readLine(); 
      count++; 
      //Enter Password 
      WebElement password = driver.findElement(By.id("pword")); 
      password.clear(); 
      password.sendKeys(strLine); 
      System.out.println(strLine); 
     } 
     in.close(); 
     br.close(); 
    } 
    catch (Exception e) 
    { 
     System.err.println("Error: " + e.getMessage()); 
    } 

,我运行到的是,它输入用户名和密码,然后贯穿一遍只有在密码投入User Name字段的问题。我知道这可能是我看起来很简单的事情。请帮忙。

回答

1

与下面的代码替换:

  try 
      { 
       FileInputStream fstream = new FileInputStream("c:/Test/userInfo.txt"); 
       // Use DataInputStream to read binary NOT text. 
       BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
       String strLine; 
       int count = 0; 

       count++; 

       while((strLine = br.readLine())!= null) 
       { 
        //Enter userName 
        WebElement userName = driver.findElement(By.id("username")); 
        userName.clear(); 
        userName.sendKeys(strLine); 
        System.out.println(strLine); 

        strLine = br.readLine(); 
        count++; 
        //Enter Password 
        WebElement password = driver.findElement(By.id("pword")); 
        password.clear(); 
        password.sendKeys(strLine); 
        System.out.println(strLine); 
       } 
       in.close(); 
       br.close(); 
      } 
      catch (Exception e) 
      { 
       System.err.println("Error: " + e.getMessage()); 
      } 

    } 

但是我不明白为什么要循环。你在文件中只有一个用户名/密码...或者很多用户名/密码?

+0

这工作很好,是的,我只有一个用户名/密码 – DarthOpto 2013-02-15 23:17:41

2

您是否尝试过使用java.util.Properties类从文本文件中读取键?它是专为这些目的,并可以用来同时读取/写入性能

示例代码

 Properties prop = new Properties(); 
     prop.load(new FileInputStream(".../Documents/userInfo.txt")); 
     String userName = prop.getProperty("username"); 
     // Password should always be stored in the char array. 
     char[] password = null; 
     if (prop.getProperty("pword") != null) { 
      password = prop.getProperty("pword").toCharArray(); 
     }