JMeter 文件处理

 

1、环境初始化时,删除同名的文件(例如:将token写入文件中前不删除原有的文件,会在文件末尾追加新的token)

File file=new File("token.txt");
if(file.exists()&&file.isFile()){
         file.delete();
     }

2、将接口返回信息写入文件中

//从用户注册接口的返回结果中获取userid、username、token,缺省值为“NULL”
if
(vars.get("userid").equals("NULL") == false&&vars.get("username").equals("NULL") == false&&vars.get("token").equals("NULL") == false){
  FileWriter fstream = new FileWriter(".\\usersinfo.csv",true);
  BufferedWriter out = new BufferedWriter(fstream);
  out.write(vars.get("userid")+","+vars.get("username")+","+vars.get("token")+"\n");
  out.close();
  fstream.close();
}
FileWriter fileWriter = new FileWriter(new File("token.txt"), true);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.append(vars.get("token")+"\n");
if (writer != null) {
  writer.close();
}
if (fileWriter != null) {
  fileWriter.close();
}

3、读取文件中数据的行数(通过文件行数可以控制循环控制器的循环次数)

import org.apache.jmeter.services.FileServer;
import com.bzj.utils.*;
import java.io.BufferedReader;
import java.io.FileReader;

String fname = vars.get("filename");
String baseDir=FileServer.getFileServer().getBaseDir(); //获取到脚本所在的目录
String filePath = baseDir+"\\data\\"+fname; //拼接成要读取文件的路径

BufferedReader br = new BufferedReader(new FileReader(filePath));
String tmpStr = "";
int rowNum = 0;
while(tmeStr = br.readLine()!=null){
    rowNum++;
}
rowNum = rowNum - 1;
vars.put("cycleNum",rowNum.toString());

 

posted @ 2019-10-18 10:46  wang小蘑菇  阅读(329)  评论(0编辑  收藏  举报