首先來讀取txt文本中的內容,輸出在控制台,直接上代碼:
import java.io.BufferedReader;import java.io.File;import java.io.FileReader; public class ReadFiledata { public static String txt2String(File file){ StringBuilder result = new StringBuilder(); try{ BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件String s = null; while((s = br.readLine())!=null){//使用readLine方法,一次讀一行result.append(System.lineSeparator()+s); } br.close(); }catch(Exception e){ e.printStackTrace(); } return result.toString(); } public static void main(String[] args){ File file = new File("F:/card.txt");//我的txt文本存放目錄,根據自己的路徑修改即可System.out.println(txt2String(file)); }}這樣我們就把txt文本中的數據讀出來了,如下截圖所示
接下來我們怎麼逐行取值把它取出來並應用到實際中呢?先上代碼:
try{ String s = ""; BufferedReader in =new BufferedReader(new FileReader("F://tel.txt")); while((s=in.readLine())!=null){ String[] split = s.split(","); String tel = split[0]; driver.findElement(By.xpath("//input[@id='register-phone']")).sendKeys(tel);//輸入正確手機號driver.findElement(By.xpath("//input[@id='register-imgcode']")).sendKeys("1234");//輸入圖片驗證碼driver.findElement(By.xpath("//input[@id='register-msgcode']")).sendKeys("123456");//輸入短信驗證碼driver.findElement(By.xpath("//input[@id='register-password']")).sendKeys("Abc123");//輸入正確密碼driver.findElement(By.xpath("//input[@id='register-confirmpassword']")).sendKeys("Abc123");//再次輸入確認密碼driver.findElement(By.xpath("//input[@id='agree']")).click();//勾選同意協議按鈕} }catch(FileNotFoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); }說明一下,代碼中的tel就是txt文本中的值,比如我要很多用戶實現註冊操作,那麼我每次都需要新的用戶,這裡用try...catch可以實現,因為我的文本內容每一行是有逗號分隔的,所以先split以逗號分隔一下,然後再以數組形式,每次取一行,直到取完txt文本中最後一行結束。當然我們可以應用到很多需要重複操作的場景中,這裡我自動化實現了若干用戶註冊的操作,很實用很簡單,分享給有需要幫助的朋友!
以上這篇java 實現讀取txt文本數據並以數組形式一行一行取值就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。