记录java+testng运行selenium(三)---xml、ini、excel、日志等配置

一: ini文件

ini目前只用处存储浏览类型及需要打开的url,ini文件放在configs文件夹下面。

读取ini代码如下:

  1 package toolskit.documents;
  2 
  3 import java.io.*;
  4 import java.util.*;
  5 
  6 /**
  7  * @ ClassName: ReadIni
  8  * @ Author: DingDong
  9  * @ Date: 2019/8/23 10:57
 10  * @ Version: 1.0
 11  * @ desc: 读取ini后缀名的文件
 12  */
 13 
 14 public class ReadIni {
 15 
 16     /**
 17      * 去除ini文件中的注释,以";"或"#"开头,顺便去除UTF-8等文件的BOM头
 18      * @param source
 19      * @return
 20      */
 21     private static String removeIniComments(String source) {
 22 
 23         String result = source;
 24 
 25         if (result.contains(";")) {
 26             result = result.substring(0, result.indexOf(";"));
 27         }
 28 
 29         if (result.contains("#")) {
 30             result = result.substring(0, result.indexOf("#"));
 31         }
 32 
 33         return result.trim();
 34     }
 35 
 36 
 37     public static Map<String, Object> readIni(String filename,String filepath) {
 38         Map<String, List<String>> listResult = new HashMap<>();
 39         Map<String, Object> result = new HashMap();
 40         String globalSection = "global";
 41 
 42         if (filepath.equalsIgnoreCase("") || filepath == null){
 43             filepath = ".\\src\\main\\java\\configs\\";
 44             filename = filepath + filename;
 45         }
 46         File file = new File(filename);
 47         BufferedReader reader = null;
 48         try {
 49             reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
 50             String str = null;
 51             String currentSection = globalSection; //处理缺省的section
 52             List<String> currentProperties = new ArrayList<>();
 53             boolean lineContinued = false;
 54             String tempStr = null;
 55 
 56             //一次读入一行(非空),直到读入null为文件结束
 57             //先全部放到listResult<String, List>中
 58             while ((str = reader.readLine()) != null) {
 59                 str = removeIniComments(str).trim(); //去掉尾部的注释、去掉首尾空格
 60 
 61                 if ("".equals(str) || str == null) {
 62                     continue;
 63                 }
 64 
 65                 //如果前一行包括了连接符'\'
 66                 if (lineContinued == true) {
 67                     str = tempStr + str;
 68                 }
 69 
 70                 //处理行连接符'\'
 71                 if (str.endsWith("\\")) {
 72                     lineContinued = true;
 73                     tempStr = str.substring(0, str.length() - 1);
 74                     continue;
 75                 } else {
 76                     lineContinued = false;
 77                 }
 78 
 79                 //是否一个新section开始了
 80                 if (str.startsWith("[") && str.endsWith("]")) {
 81                     String newSection = str.substring(1, str.length() - 1).trim();
 82 
 83                     //如果新section不是现在的section,则把当前section存进listResult中
 84                     if (!currentSection.equals(newSection)) {
 85                         listResult.put(currentSection, currentProperties);
 86                         currentSection = newSection;
 87 
 88                         //新section是否重复的section
 89                         //如果是,则使用原来的list来存放properties
 90                         //如果不是,则new一个List来存放properties
 91                         currentProperties = listResult.get(currentSection);
 92                         if (currentProperties == null) {
 93                             currentProperties = new ArrayList<>();
 94                         }
 95                     }
 96                 } else {
 97                     currentProperties.add(str);
 98                 }
 99             }
100             //把最后一个section存进listResult中
101             listResult.put(currentSection, currentProperties);
102 
103             reader.close();
104 
105 
106         } catch (IOException e) {
107             e.printStackTrace();
108         } finally {
109             if (reader != null) {
110                 try {
111                     reader.close();
112                 } catch (IOException e1) {
113                 }
114             }
115         }
116 
117 
118         //整理拆开name=value对,并存放到MAP中:
119         //从listResult<String, List>中,看各个list中的元素是否包含等号“=”,如果包含,则拆开并放到Map中
120         //整理后,把结果放进result<String, Object>中
121         for (String key : listResult.keySet()) {
122             List<String> tempList = listResult.get(key);
123 
124             //空section不放到结果里面
125             if (tempList == null || tempList.size() == 0) {
126                 continue;
127             }
128 
129             if (tempList.get(0).contains("=")) { //name=value对,存放在MAP里面
130                 Map<String, String> properties = new HashMap<>();
131                 for (String s : tempList) {
132                     int delimiterPos = s.indexOf("=");
133                     //处理等号前后的空格
134                     properties.put(s.substring(0, delimiterPos).trim(), s.substring(delimiterPos + 1, s.length()).trim());
135                 }
136                 result.put(key, properties);
137             } else { //只有value,则获取原来的list
138                 result.put(key, listResult.get(key));
139             }
140         }
141         return result;
142     }
143 
144 }

 

二: xml文件读取

xml文件主要存储excel所在路径以及用例类所对应的sheet名

参考:https://www.jianshu.com/p/8e333a0ec42a

代码如下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @ ClassName: toolskit.documents
 * @ Author: DingDong
 * @ Date: 2019/10/21 14:36
 * @ Version: 1.0
 * @ desc:
 */

public class XmlUtil {

    public static List getXmlComent(String path){
        //获取xml文件完全路径
        System.out.println("xml·path"+path);

        List contList=new ArrayList();
        //dom4j中读取xml文件的方法
        SAXReader saxR=new SAXReader();
        try {
            Document doc=saxR.read(path);
            //存放顶结点
            Element eleroot=doc.getRootElement();
            //parMap,存放顶结点下一级结点
            Map parMap=null;
            Map sonMap=null;
            for(Iterator i=eleroot.elementIterator();i.hasNext();){
                //parMap中存放的结点的子结点
                parMap=new HashMap();
                sonMap=new HashMap();
                Element elepar=(Element)i.next();
                for(Iterator j=elepar.elementIterator();j.hasNext();){
                    Element eleSon=(Element)j.next();
                    System.out.println("+++++"+eleSon.getName()+"    "+ eleSon.getText());
                    sonMap.put(eleSon.getName(), eleSon.getText());
                }

                parMap.put(elepar.getName(),sonMap);
                System.out.println("*****"+elepar.getName() +"*********" + sonMap);
                contList.add(parMap);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return contList;
    }
}

其中parMap和sonMap要在for里面清空已有的内容,不然contList存储的数据都是重复的

 

 

四:excel文件读写

ExcelOperating作为父类,用于区分文件类型及文件是否存在

ReadExcel:用于用户读取excel的内容并存在Map里面然后返回

WriteExcel :让用户将输入写入excel里面

ExcelOperating代码如下:

  1 package toolskit.documents;
  2 
  3 import java.io.*;
  4 import java.text.DecimalFormat;
  5 import java.text.SimpleDateFormat;
  6 import java.util.Date;
  7 
  8 import org.apache.commons.io.IOCase;
  9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 10 import org.apache.poi.ss.usermodel.*;
 11 
 12 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 13 import org.apache.poi.ss.usermodel.DateUtil;
 14 
 15 
 16 
 17 
 18 
 19 public class ExcelOperating {
 20 
 21     private final String XLS_VERSION = "xls";
 22     private final String XLSX_VERSION = "xlsx";
 23 
 24     /**
 25      * 判断Excel的版本,获取Workbook
 26      * @param fileName 文件名
 27      * @return sheet对象
 28      */
 29     public Workbook distinguishWorkbook(String fileName) {
 30         Workbook workbook = null;
 31         InputStream is = null;
 32         try {
 33             File file = new File(fileName);
 34             is = new FileInputStream(file);
 35 
 36             if (IOCase.SENSITIVE.checkEndsWith(fileName, XLS_VERSION)) {
 37 
 38                 workbook = new HSSFWorkbook(is);
 39 
 40             } else if (IOCase.SENSITIVE.checkEndsWith(fileName, XLSX_VERSION)) {
 41 
 42                 workbook = new XSSFWorkbook(is);
 43 
 44             } else {
 45                 System.out.println("该文件不是excle表格:" + fileName);
 46 
 47             }
 48         } catch (FileNotFoundException e) {
 49             System.out.println(">>>>>>>>>>  读取excel文件时出错了!!!");
 50             e.printStackTrace();
 51         } catch (IOException e) {
 52             System.out.println(">>>>>>>>>>  读取excel文件时出错了!!!");
 53             e.printStackTrace();
 54         }finally {
 55             if (is != null) {
 56                 try {
 57                     is.close();
 58                 } catch (IOException e) {
 59                     e.printStackTrace();
 60                 }
 61             }
 62         }
 63         return workbook;
 64     }
 65 
 66 
 67     public   String getIntTypeValue(Cell cell) {
 68         String cellValue = "";
 69         double value = cell.getNumericCellValue();
 70         if (cell.getCellStyle().getDataFormat() == 176) {
 71 
 72             // 处理自定义日期格式:M月D日(通过判断单元格的格式id解决,ID的值是58)
 73             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 74             Date date = DateUtil.getJavaDate(value);
 75             cellValue = sdf.format(date);
 76 
 77         } else {
 78             CellStyle style = cell.getCellStyle();
 79             DecimalFormat format = new DecimalFormat();
 80             String temp = style.getDataFormatString();
 81 
 82             // 把数字当成String来读,避免出现1读成1.0的情况.这个方式没这么灵活
 83             //        if (cell.getCellType() == CellType.NUMERIC) {
 84             //            cell.setCellType(CellType.STRING);
 85             //        }
 86 
 87             // 单元格设置成常规
 88             if (temp.equals("General")) {
 89                 format.applyPattern("#");
 90             }
 91             cellValue = format.format(value);
 92         }
 93         return cellValue;
 94     }
 95 
 96     /**
 97      * 判断获取当前内容的格式,然后进行返回内容
 98      * 把单元格的内容转为字符串
 99      * 高版本的import org.apache.poi.ss.usermodel.CellType变为了import org.apache.poi.ss.usermodel.Cell;
100      * 同时cellRowName.setCellType(CellType.STRING);变为了cellRowName.setCellType(Cell.CELL_TYPE_STRING);
101      * 并且xssfCell.getCellTypeEnum()变成xssfCell.getCellType()
102      * CellType                    类型            值
103      * NUMERIC                    数值型            0
104      * STRING                    字符串型        1
105      * FORMULA                    公式型            2
106      * BLANK                    空值            3
107      * BOOLEAN                    布尔型            4
108      * ERROR                    错误            5
109      * @param cell 单元格
110      * @return 字符串
111      */
112     @SuppressWarnings("deprecation")
113     public  String getCellValue(Cell cell) {
114         String cellValue = "";
115         if (cell == null) {
116             return cellValue;
117         }
118 
119         //判断数据的类型,低版本中switch里面的case写法不一样。
120         CellType cellType = cell.getCellType();
121 
122         switch (cellType) {
123             case NUMERIC: //数字
124                 cellValue = getIntTypeValue(cell);
125                 break;
126             case STRING: //字符串
127                 cellValue = String.valueOf(cell.getStringCellValue());
128                 break;
129             case BOOLEAN: //Boolean
130                 cellValue = String.valueOf(cell.getBooleanCellValue());
131 
132                 break;
133             case FORMULA: //公式
134                 cellValue = String.valueOf(cell.getCellFormula());
135                 break;
136             case BLANK: //空值
137                 cellValue = "";
138                 break;
139             case ERROR: //故障
140                 cellValue = "非法字符";
141                 break;
142             case _NONE: //故障
143                 cellValue = "非法字符";
144                 break;
145             default:
146                 cellValue = "未知类型";
147                 break;
148         }
149         return cellValue;
150     }
151 
152 }

ReadExcel代码如下:

  1 package toolskit.documents;
  2 
  3 import java.io.*;
  4 import java.util.*;
  5 
  6 import org.apache.poi.ss.usermodel.*;
  7 
  8 
  9 public class ReadExcel extends ExcelOperating {
 10 //    public static void main(String[] args) {
 11 //        ReadExcel re = new ReadExcel();
 12 //        String load = "C:\\Users\\LGYY-USER\\Desktop\\红包发放.xlsx";
 13 
 14 
 15 //         方式一: 指定sheet来读取
 16 //        List<Map<String, String>> excelList = re.readExcel(load, "登录");
 17 //        System.out.println("从excel读取数据并开始使用:");
 18 //        for (Map<String, String> list : excelList) {
 19 //            System.out.println(list);
 20 //            for (Map.Entry<String, String> entry : list.entrySet()) {
 21 //                System.out.println(entry.getValue());
 22 //            }
 23 //            System.out.println();
 24 //        }
 25 
 26 //         方式二: 读取单个文件,单行数据
 27 //            Map<String, String> stringStringMap = re.singleReadXlsx(load, "登录", 2);
 28 //        System.out.println(stringStringMap);
 29 //            for(Map.Entry<String, String> entry : stringStringMap.entrySet()){
 30 //                System.out.print("Key = "+entry.getKey()+",value="+entry.getValue() + "\n");
 31 //            }
 32 
 33 //         方式三: 读取全部sheet的数据
 34 //        List<Map<Integer, Object>> lists = re.wholeReadXlsx(load);
 35 //        for (Map<Integer, Object> i : lists) {
 36 //            System.out.print(i);
 37 //        }
 38 
 39 //    }
 40 
 41     /**
 42      * 通过Workbook来读取excle表格上的数据
 43      *
 44      * @param load 文件所在路径
 45      * @return 获取到的数据
 46      */
 47     public List<Map<Integer, Object>> wholeReadXlsx(String load) {
 48         // excel中第几列 : 对应的表头
 49         Map<Integer, String> colAndNameMap = new HashMap<Integer, String>();
 50         List<Map<Integer, Object>> resultList = new ArrayList<Map<Integer, Object>>();
 51         Workbook wb = null;
 52         try {
 53             wb = distinguishWorkbook(load);
 54             for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
 55                 //获取sheet数据
 56                 Sheet st = wb.getSheetAt(sheetIndex);
 57                 //遍历一个sheet中每一行
 58                 for (int rowIndex = 0; rowIndex <= st.getLastRowNum(); rowIndex++) {
 59                     // 表头:值
 60                     Map<Integer, Object> nameAndValMap = new HashMap<Integer, Object>();
 61                     // 获取到一行数据
 62                     Row row = st.getRow(rowIndex);
 63                     for (int cellIndex = 0; cellIndex < row.getPhysicalNumberOfCells(); cellIndex++) {
 64 
 65                         if (rowIndex == 0) {
 66                             colAndNameMap.put(cellIndex, row.getCell(cellIndex).getStringCellValue());
 67                         } else if (!colAndNameMap.isEmpty()) {
 68                             nameAndValMap.put(cellIndex, getCellValue(row.getCell(cellIndex)));
 69                         }
 70                     }
 71                     if (!nameAndValMap.isEmpty()) {
 72                         resultList.add(nameAndValMap);
 73                     }
 74                 }
 75             }
 76             return resultList;
 77         } catch (Exception e) {
 78             System.out.println(">>>>>>>>>>  读取excel文件时出错了!!!");
 79             e.printStackTrace();
 80         } finally {
 81             try {
 82                 wb.close();
 83             } catch (IOException e) {
 84                 e.printStackTrace();
 85             }
 86         }
 87         return null;
 88     }
 89 
 90 
 91     /**
 92      * 读取指定工作薄里的指定行的内容
 93      * load文档所在地
 94      * numSheet当前文档中所读写的工作薄
 95      * rowNum当前工作薄中的第几个数据
 96      * @param load 文件所在路径
 97      * @param sheetName sheet表格名字
 98      * @param rowNum 指定行数
 99      * @return 找到的全部数据
100      */
101     public Map<String, String> singleReadXlsx(String load, String sheetName, int rowNum) {
102         Workbook xssfWorkbook = distinguishWorkbook(load);
103         Map<String, String> aMap = new HashMap<String, String>();
104         Sheet xssfSheet;
105         if (sheetName.equals("")) {
106             // 默认取第一个子表
107             xssfSheet = xssfWorkbook.getSheetAt(0);
108         } else {
109             xssfSheet = xssfWorkbook.getSheet(sheetName);
110         }
111 
112         if (xssfSheet != null) {
113             // 获取指定行
114             Row xssfRow = xssfSheet.getRow(rowNum);//获取该行的全部数据
115             if (xssfRow != null) {
116 
117                 int firstCellNum = (int) xssfRow.getFirstCellNum();// 首列
118                 int lastCellNum = (int) xssfRow.getLastCellNum();// 最后一列
119 
120                 for (int col = firstCellNum; col < lastCellNum; col++) {
121                     String sEnum = col + "";
122                     aMap.put(sEnum, getCellValue(xssfRow.getCell(col)));
123                 }
124             } else {
125                 System.out.println("xssfRow为空");
126             }
127         }
128 
129         return aMap;
130     }
131 
132 
133     /**
134      *  指定表格中行的数据长度
135      * @param load 文件名
136      * @param nameSheet 表格名字
137      * @return 表格行的总数
138      */
139     public int singleXlsx(String load, String nameSheet) {
140         int row = 0;
141         // 获取每一个工作薄
142         Sheet sheetAt = distinguishWorkbook(load).getSheet(nameSheet);
143         if (sheetAt != null) {
144             row = sheetAt.getLastRowNum();
145         }
146         return row;
147 
148     }
149 
150     /**
151      * 读取Excel文件中指定sheet的内容
152      *
153      * @param load      excel文件的所在路径
154      * @param sheetName sheet名字
155      * @return 以List返回excel中内容
156      */
157     public List<Map<String, String>> readExcel(String load, String sheetName) {
158 
159         Workbook xssfWorkbook = distinguishWorkbook(load);
160 
161         //定义工作表
162         Sheet xssfSheet;
163 
164         if (sheetName.equals("")) {
165             // 默认取第一个子表
166             xssfSheet = xssfWorkbook.getSheetAt(0);
167         } else {
168             xssfSheet = xssfWorkbook.getSheet(sheetName);
169         }
170 
171         List<Map<String, String>> list = new ArrayList<Map<String, String>>();
172 
173         // 默认第一行为标题行,index = 0
174         Row titleRow = xssfSheet.getRow(0);
175 
176         // 根据第一行返回该行中单元格的数量
177         int cellNumber = titleRow.getPhysicalNumberOfCells();
178 
179         // 返回sheet标中行的总数
180         int rownumber = xssfSheet.getPhysicalNumberOfRows();
181 
182         // 循环取每行的数据
183         for (int rowIndex = 1; rowIndex < rownumber; rowIndex++) {
184             Row xssfRow = xssfSheet.getRow(rowIndex);
185             if (xssfRow == null) {
186                 continue;
187             }
188 
189             Map<String, String> map = new LinkedHashMap<String, String>();
190 
191             //循环取每个单元格(cell)的数据
192             for (int cellIndex = 0; cellIndex < cellNumber; cellIndex++) {
193                 Cell titleCell = titleRow.getCell(cellIndex);
194                 Cell xssfCell = xssfRow.getCell(cellIndex);
195                 map.put(getCellValue(titleCell), getCellValue(xssfCell));
196             }
197             list.add(map);
198         }
199         return list;
200     }
201 
202     /**
203      * 把一个Map中的所有键和值分别放到一个list中,
204      * 再把这两个list整个放到一个大的list里面,即 [ [key1,key2,key3...] , [value1,value2,value3...] ]
205      *
206      * @param map 需要转换的map
207      * @return 已转换后的list
208      */
209     public static List<List> convertMapToList(Map map) {
210         List<List> list = new ArrayList<List>();
211         List<String> key_list = new LinkedList<String>();
212         List<String> value_list = new LinkedList<String>();
213 
214         Set set = map.entrySet();
215         Iterator<Map.Entry<String, String>> iter1 = set.iterator();
216         while (iter1.hasNext()) {
217             key_list.add(iter1.next().getKey());
218         }
219         list.add(key_list);
220 
221         Collection<String> value = map.values();
222         Iterator<String> iter2 = value.iterator();
223         while (iter2.hasNext()) {
224             value_list.add(iter2.next());
225         }
226         list.add(value_list);
227         return list;
228     }
229 }

 

WriteExcel写法如下:很少使用这个类

package toolskit.documents;

import java.io.*;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



public class WriteExcel extends ExcelOperating{

    // 当前文件已经存在
    private String excelPath = "E:/MyFirstExcel.xlsx";

    // 从第几行插入进去
    private int insertStartPointer;

    // 根据工作薄名进行插入
    private String sheetName;

    // 根据工作薄所在位置进行插入
    private int sheetInsert = 0;

    public WriteExcel(String excelPath, int insertStartPointer, String sheetName, int sheetInsert) {
        this.excelPath = excelPath;
        this.insertStartPointer = insertStartPointer;
        this.sheetName = sheetName;
        this.sheetInsert = sheetInsert;
    }

    public WriteExcel() {
    }

    /**
     * 总的入口方法
     */
    public static void main(String[] args){
        WriteExcel crt = new WriteExcel();
        int i = new ReadExcel().singleXlsx(crt.excelPath, "sheet");
        crt.insertStartPointer = i + 1;
        crt.insertRows();
    }

    /**
     * 在已有的Excel文件中插入一行新的数据的入口方法
     */
    public void insertRows() {
        Workbook wb = returnWorkBookGivenFileHandle();
        // XSSFSheet sheet1 = wb.getSheet(sheetName);
        sheetName = wb.getSheetName(sheetInsert);
        Sheet sheet = wb.getSheet(sheetName);
        Row row = createRow(sheet, insertStartPointer);
        createCell(row);
        saveExcel(wb);

    }

    /**
     * 保存工作薄
     *
     * @param wb
     */
    private void saveExcel(Workbook wb) {
        FileOutputStream fileOut;
        try {
            fileOut = new FileOutputStream(excelPath);
            wb.write(fileOut);
            fileOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建要出入的行中单元格
     *
     * @param row
     * @return
     */
    private Cell createCell(Row row) {
        Cell cell = row.createCell((short) 0);
        cell.setCellValue(999999);
        row.createCell(1).setCellValue(1.2);
        row.createCell(2).setCellValue("This is a string cell");
        return cell;
    }

    /**
     * 得到一个已有的工作薄的POI对象
     *
     * @return
     */
    private Workbook returnWorkBookGivenFileHandle() {
        Workbook wb = null;
        File f = new File(excelPath);
        try {
            if (f != null) {
                wb = distinguishWorkbook(excelPath);
            }
        } catch (Exception e) {
            return null;
        }
        return wb;
    }

    /**
     * 找到需要插入的行数,并新建一个POI的row对象
     *
     * @param sheet
     * @param rowIndex
     * @return
     */
    private Row createRow(Sheet sheet, Integer rowIndex) {
        Row row = null;
        if (sheet.getRow(rowIndex) != null) {
            int lastRowNo = sheet.getLastRowNum();
            sheet.shiftRows(rowIndex, lastRowNo, 1);
        }
        row = sheet.createRow(rowIndex);
        return row;
    }

    /**
     * 把内容写入Excel
     *
     * @param list         传入要写的内容,此处以一个List内容为例,先把要写的内容放到一个list中
     * @param outputStream 把输出流怼到要写入的Excel上,准备往里面写数据
     */
    public void writeExcel(List<List> list, OutputStream outputStream) {
        //创建工作簿
        XSSFWorkbook xssfWorkbook;
        xssfWorkbook = new XSSFWorkbook();

        //创建工作表
        XSSFSheet xssfSheet;
        xssfSheet = xssfWorkbook.createSheet();

        //创建行
        XSSFRow xssfRow;

        //创建列,即单元格Cell
        XSSFCell xssfCell;

        //把List里面的数据写到excel中
        for (int i = 0; i < list.size(); i++) {
            //从第一行开始写入
            xssfRow = xssfSheet.createRow(i);
            //创建每个单元格Cell,即列的数据
            List sub_list = list.get(i);
            for (int j = 0; j < sub_list.size(); j++) {
                xssfCell = xssfRow.createCell(j); //创建单元格
                xssfCell.setCellValue((String) sub_list.get(j)); //设置单元格内容
            }
        }

        //用输出流写到excel
        try {
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 

五:日志输出

日志输出一般有两个方式:

1. 定义全局的System.out.println统一进行输出

2. 由log日志进行输出

 

由System.out.println输出的模板:

package toolskit;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @ ClassName: SystemOut
 * @ Author: DingDong
 * @ Date: 2019/8/13 11:33
 * @ Version: 1.0
 * @ desc:
 */


public class SystemOut {

    public static void textStringOut(String data, String text) {
        System.out.println(data + ":" + text);
    }

    public static void textStringOut(String status, String data, String text) {
        System.out.println(status + ":" + data + ":" + text);
    }

    public static void textStringOut(String text) {
        System.out.println(text);
    }

    /**
     * 用例成功,并且编辑成功
     *
     * @param massage   用例编号
     * @param parameter 用例输入的内容
     */
    public static void caseSuccess(String massage, String parameter) {
        System.out.println(massage + "用例执行成功,编辑内容为:" + parameter);
    }

    /**
     * 编辑判断成功
     *
     * @param massage 执行编号
     */
    public static void caseEditSuccess(String massage) {
        System.out.println(massage + "用例中的元素对象不需要编辑,程序判断成功。。");
    }

    /**
     * 用例执行成功
     *
     * @param massage
     */
    public static void caseSuccess(String massage) {
        System.out.println(massage + "用例执行成功");
    }


    /**
     * 用例执行失败,并且打印出输入信息
     *
     * @param massage
     */
    public static void caseFail(String massage) {
        System.out.println(massage + "用例执行失败。。。。");
    }

    /**
     * 不需要进行编辑时发生失败
     *
     * @param massage 用例编号
     */
    public static void caseEditFail(String massage) {
        System.out.println(massage + "用例中的元素对象不需要编辑,程序判断失败。");
    }

    public static void caseFail(String massage, String parameter) {
        System.out.println(massage + "用例执行失败,编辑内容为:" + parameter);
    }

    /**
     * @param li
     */
    public static void getStringOut(List<List> li) throws InterruptedException {
        textStringOut("打印list开始" + li.size());
        for (int i = 0; i < li.size(); i++) {
            textStringOut(li.get(i).toString());
        }
    }


    public static void getStringOut(Map<String, String> aMap) throws InterruptedException {
        textStringOut("打印list开始" + aMap.size());
        Iterator<Map.Entry<String, String>> iterator = aMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            System.out.println("Key = " + next.getKey() + ", Value = " + next.getValue());
        }
    }
}

 

log日志输出:

1. 在resources文件夹下面创建以下两个文件:common-logging.properties 和 log4j.properties

2. 配置两个dependency,分别是commons-logging 和 log4j

common-logging.properties 里面内容为:

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

 

log4j.properties 里面内容为:

#设置logger级别DEBUG、INFO、WRNING、ERROR和输出格式A、B、C或D
log4j.rootLogger=debug , stdout , D , E
### 输出INFO级别以上的日志到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### 输出到日志文件 ###
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File=E:/logs/log.log
log4j.appender.D.Append=true
## 输出DEBUG级别以上的日志
log4j.appender.D.Threshold=DEBUG
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %c{1}:%L %m%n
### 保存异常信息到单独文件 ###
log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
## 异常日志文件名
log4j.appender.E.File=E:/logs/error.log
log4j.appender.E.Append=true
## 只输出ERROR级别以上的日志!!!
log4j.appender.E.Threshold=ERROR
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

pom文件配置:dependency

 <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <!--日志文件-->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

 

log代码:

package toolskit;

import org.apache.log4j.Logger;

/**
 * @ ClassName: InformationLog
 * @ Author: DingDong
 * @ Date: 2019/8/9 17:39
 * @ Version: 1.0
 * @ desc:
 */
public class InformationLog {
    protected static final Logger logger = Logger.getLogger(InformationLog.class);

    public static void inputLogInfo(String infoData) {
        logger.info(infoData);
    }

    public static void inputLogDebug(String infoData) {
        logger.debug(infoData);
    }

    public static void inputLogWarn(String infoData) {
        logger.warn(infoData);
    }

    public static void inputLogError(String infoData) {
        logger.error(infoData);
    }

    public static void inputLogFatal(String infoData) {
        logger.fatal(infoData);
    }

}

 

 

 

 

 

说明:

定义文件地址的时候,都是写死;文件地址这边写死(动态又高级的写法不懂如何编写)

 

posted on 2019-10-22 15:50  叮咚丶哈哈  阅读(402)  评论(0编辑  收藏  举报

导航