首先來讀取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("http://input[@id='register-phone']")).sendKeys(tel);//輸入正確手機號 driver.findElement(By.xpath("http://input[@id='register-imgcode']")).sendKeys("1234");//輸入圖片驗證碼 driver.findElement(By.xpath("http://input[@id='register-msgcode']")).sendKeys("123456");//輸入短信驗證碼 driver.findElement(By.xpath("http://input[@id='register-password']")).sendKeys("Abc123");//輸入正確密碼 driver.findElement(By.xpath("http://input[@id='register-confirmpassword']")).sendKeys("Abc123");//再次輸入確認密碼 driver.findElement(By.xpath("http://input[@id='agree']")).click();//勾選同意協議按鈕 } }catch(FileNotFoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); }
說明一下,代碼中的tel就是txt文本中的值,比如我要很多用戶實現注冊操作,那么我每次都需要新的用戶,這里用try...catch可以實現,因為我的文本內容每一行是有逗號分隔的,所以先split以逗號分隔一下,然后再以數組形式,每次取一行,直到取完txt文本中最后一行結束。當然我們可以應用到很多需要重復操作的場景中,這里我自動化實現了若干用戶注冊的操作,很實用很簡單,分享給有需要幫助的朋友!
以上這篇java 實現讀取txt文本數據并以數組形式一行一行取值就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。