2015-10-14 39 views
0

對於我們團隊構建的框架,我們需要製作一個文本文件,我們將在運行測試之前編輯一個文本文件。該文本文件有兩行 - 我們的Web應用程序的URL,以及包含測試用例的Excel文件的位置。將.txt文件中的行用作測試中的數據

現在,爲了閱讀文件,我一直在使用Scanner

private static void readFile(String fileName) { 
    try { 
    File file = new File(fileName); 
    Scanner scanner = new Scanner(file); 
    while (scanner.hasNextLine()) { 
     System.out.println(scanner.nextLine()); 
    } 
    scanner.close(); 
    } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
    } 
} 

我的代碼行話是不是最好的所以儘量讓我要問:

有人能指出我在提取這兩條線的右方向(URL和Excel路徑)從文本文件中,將它們分配給兩個不同的變量/對象/函數/任何你真正想要調用它們的東西,並將它們傳遞到主測試腳本中,以便測試腳本知道它想做什麼。

我畫了一幅畫。花了100個小時。

100 hours in paint

+0

該文件的格式是什麼?就目前而言,只要每條路徑都在自己的路線上,您的代碼應該能夠正確地讀取它們。 – npinti

+1

屬性對象怎麼樣? https://docs.oracle.com/javase/tutorial/essential/environment/properties.html – svarog

+1

格式爲.txt。這是一個小記事本。它讀得很好,我只是想知道如何讓它讀取它,而不是傳遞給我的腳本。 @svarog還沒有使用過屬性。我會馬上閱讀,並讓你知道。 – jagdpanzer

回答

1
private String urlText; 
private String excelLocation; 

private static void readFile(String fileName) { 
    try { 
    int lineNumber = 0; 
    File file = new File(fileName); 
    Scanner scanner = new Scanner(file); 
    while (scanner.hasNextLine()) { 
     lineNumber++; 
     if (lineNumber == 1){ 
     urlText = scanner.nextLine(); 
     } 
     else{ 
     excelLocation = scanner.nextLine(); 
    } 
    scanner.close(); 
    } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
    } 
} 

如果您想更詳細,你還可以使用LineNumberReader。在這裏看到:How to get line number using scanner

1

可以使用Properties對象

寫入文件:

Properties prop = new Properties(); 
OutputStream output = null; 

try { 

    output = new FileOutputStream("yourfile.txt"); 

    // set the properties value 
    prop.setProperty("database", "localhost"); 
    prop.setProperty("dbuser", "john"); 
    prop.setProperty("dbpassword", "password"); 

    // save properties to project root folder 
    prop.store(output, null); 

} catch (IOException io) { 
    io.printStackTrace(); 
} finally { 
    if (output != null) { 
     try { 
      output.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

閱讀:

Properties prop = new Properties(); 
InputStream input = null; 

try { 

    input = new FileInputStream("yourfile.txt"); 

    // load a properties file 
    prop.load(input); 

    // get the property value and print it out 
    System.out.println(prop.getProperty("database")); 
    System.out.println(prop.getProperty("dbuser")); 
    System.out.println(prop.getProperty("dbpassword")); 

} catch (IOException ex) { 
    ex.printStackTrace(); 
} finally { 
    if (input != null) { 
     try { 
      input.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

,你會得到一個「yourfile.txt 「與這些行的文件:

dbpassword=password 
database=localhost 
dbuser=john 

我採取的代碼來自:http://www.mkyong.com/java/java-properties-file-examples/

相關問題