2013-02-15 49 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(); 
     } 
相關問題