Java学习-016-CSV 文件读取实例源代码

时间:2023-03-08 21:12:03

上文(CSV文件写入)讲述了日常自动化测试过程中将测试数据写入 CSV 文件的源码,此文主要讲述如何从 CSV 文件获取测试过程中所需的参数化数据。敬请各位小主参阅,若有不足之处,敬请大神指正,不胜感激!

不多言,小二上码咯。。。

CSV文件读取源代码如下所示,敬请参阅!

     /**
* @function Read File: CSV
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium main.java.aaron.java.tools FileUtils.java csvRead, 2014-11-25 15:55:52 Exp $
*
* @param filename : CSV file
* @param delimiter : content split char
* @param encoding : file encoding
*
* @return ArrayList<String[]> file content
*/
public ArrayList<String[]> csvRead(String filename, char delimiter, String encoding){
ArrayList<String[]> csvdata = new ArrayList<String[]>(); // CSV 数据
CsvReader csvreader = null; /* 参数校验: 为null或空字符串时, 抛出参数非法异常 */
if (filename == null || "".equals(filename) || !assertFileType(filename, "CSV")) {
throw new IllegalArgumentException();
} /* 分隔符默认处理, 若分割符号为空, 则默认 ‘,’ */
if ("".equals(delimiter)) {
delimiter = ',';
} try {
csvreader = new CsvReader(filename, delimiter, Charset.forName(encoding)); /* 跳过表头, 若是需要表头则注释词句即可 */
// csvreader.readHeaders(); while (csvreader.readRecord()) {
csvdata.add(csvreader.getValues());
}
} catch (IOException ioe) {
this.message = "文件 {" + filename + "} 读取失败!";
this.logger.error(this.message, ioe); return null;
} return csvdata;
}

CSV文件读取源码

CSV文件读取测试源码如下所示,敬请参阅!

     /**
* Test : read|write CSV file
*
* @author Aaron.ffp
* @version V1.0.0: autoUISelenium test.java.aaron.java.tools FileUtilsTest.java test_csvWrite_and_csvRead, 2014-11-25 16:28:20 Exp $
*
*/
@Test
public void test_csvWrite_and_csvRead(){
this.message = "\n\n\nTEST:FileUtils.csvWrite(String filename, char delimiter, String encoding, ArrayList<String[]> csvdata)";
this.logger.debug(this.message); this.fu = new FileUtils(); // you should change this to local file path
String filename = this.constantslist.PROJECTHOME + this.constantslist.FILESEPARATOR +
"testng-temp" + this.constantslist.FILESEPARATOR + "createfile.csv"; ArrayList<String[]> csvdata = new ArrayList<String[]>();
String[] rows; // init csv data
for (int i = 0; i < 20; i++) {
rows = new String[10]; for (int j = 0; j < rows.length; j++) {
rows[j] = i + " = " + j;
} csvdata.add(rows);
} // init csv file data
boolean w = this.fu.csvWrite(filename, ',', "UTF-8", csvdata); // get actual data and compare data
boolean r = this.fu.csvRead(filename, ',', "UTF-8").get(2)[2].toString().equals("2 = 2"); Assert.assertEquals(w, r, "Test case failed.");
}

CSV文件读取测试源码

至此, Java学习-016-CSV 文件读取实例源代码 顺利完结,希望此文能够给初学 Java 的您一份参考。

最后,非常感谢亲的驻足,希望此文能对亲有所帮助。热烈欢迎亲一起探讨,共同进步。非常感谢! ^_^