java如何读取txt文本数据并以数组形式一行一行取值

首先来读取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文本中最后一行结束。当然我们可以应用到很多需要重复操作的场景中,这里我自动化实现了若干用户注册的操作,很实用很简单,分享给有需要帮助的朋友!


  • 12
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值