java++記錄+運行_記錄java+testng運行selenium(三)---xml、ini、excel、日志等配置

一: ini文件

ini目前只用處存儲瀏覽類型及需要打開的url,ini文件放在configs文件夾下面。

讀取ini代碼如下:

1 packagetoolskit.documents;2

3 import java.io.*;4 import java.util.*;5

6 /**

7 * @ ClassName: ReadIni8 * @ Author: DingDong9 * @ Date: 2019/8/23 10:5710 * @ Version: 1.011 * @ desc: 讀取ini后綴名的文件12 */

13

14 public classReadIni {15

16 /**

17 * 去除ini文件中的注釋,以";"或"#"開頭,順便去除UTF-8等文件的BOM頭18 *@paramsource19 *@return

20 */

21 private staticString 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 returnresult.trim();34 }35

36

37 public static MapreadIni(String filename,String filepath) {38 Map> listResult = new HashMap<>();39 Map result = newHashMap();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 = newFile(filename);47 BufferedReader reader = null;48 try{49 reader = new BufferedReader(new InputStreamReader(newFileInputStream(file)));50 String str = null;51 String currentSection = globalSection; //處理缺省的section

52 List currentProperties = new ArrayList<>();53 boolean lineContinued = false;54 String tempStr = null;55

56 //一次讀入一行(非空),直到讀入null為文件結束57 //先全部放到listResult中

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是否重復的section89 //如果是,則使用原來的list來存放properties90 //如果不是,則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中,看各個list中的元素是否包含等號“=”,如果包含,則拆開并放到Map中120 //整理后,把結果放進result中

121 for(String key : listResult.keySet()) {122 List 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 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 returnresult;142 }143

144 }

二: xml文件讀取

xml文件主要存儲excel所在路徑以及用例類所對應的sheet名

代碼如下:

importjava.util.ArrayList;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importorg.dom4j.Document;importorg.dom4j.DocumentException;importorg.dom4j.Element;importorg.dom4j.io.SAXReader;/*** @ ClassName: toolskit.documents

* @ Author: DingDong

* @ Date: 2019/10/21 14:36

* @ Version: 1.0

* @ desc:*/

public classXmlUtil {public staticList getXmlComent(String path){//獲取xml文件完全路徑

System.out.println("xml·path"+path);

List contList=newArrayList();//dom4j中讀取xml文件的方法

SAXReader saxR=newSAXReader();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=newHashMap();

sonMap=newHashMap();

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();

}returncontList;

}

}

其中parMap和sonMap要在for里面清空已有的內容,不然contList存儲的數據都是重復的

四:excel文件讀寫

ExcelOperating作為父類,用于區分文件類型及文件是否存在

ReadExcel:用于用戶讀取excel的內容并存在Map里面然后返回

WriteExcel :讓用戶將輸入寫入excel里面

ExcelOperating代碼如下:

1 packagetoolskit.documents;2

3 import java.io.*;4 importjava.text.DecimalFormat;5 importjava.text.SimpleDateFormat;6 importjava.util.Date;7

8 importorg.apache.commons.io.IOCase;9 importorg.apache.poi.hssf.usermodel.HSSFWorkbook;10 import org.apache.poi.ss.usermodel.*;11

12 importorg.apache.poi.xssf.usermodel.XSSFWorkbook;13 importorg.apache.poi.ss.usermodel.DateUtil;14

15

16

17

18

19 public classExcelOperating {20

21 private final String XLS_VERSION = "xls";22 private final String XLSX_VERSION = "xlsx";23

24 /**

25 * 判斷Excel的版本,獲取Workbook26 *@paramfileName 文件名27 *@returnsheet對象28 */

29 publicWorkbook distinguishWorkbook(String fileName) {30 Workbook workbook = null;31 InputStream is = null;32 try{33 File file = newFile(fileName);34 is = newFileInputStream(file);35

36 if(IOCase.SENSITIVE.checkEndsWith(fileName, XLS_VERSION)) {37

38 workbook = newHSSFWorkbook(is);39

40 } else if(IOCase.SENSITIVE.checkEndsWith(fileName, XLSX_VERSION)) {41

42 workbook = newXSSFWorkbook(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 returnworkbook;64 }65

66

67 publicString 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 = newDecimalFormat();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 returncellValue;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 數值型 0104 * STRING 字符串型 1105 * FORMULA 公式型 2106 * BLANK 空值 3107 * BOOLEAN 布爾型 4108 * ERROR 錯誤 5109 *@paramcell 單元格110 *@return字符串111 */

112 @SuppressWarnings("deprecation")113 publicString getCellValue(Cell cell) {114 String cellValue = "";115 if (cell == null) {116 returncellValue;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 returncellValue;150 }151

152 }

ReadExcel代碼如下:

1 packagetoolskit.documents;2

3 import java.io.*;4 import java.util.*;5

6 import org.apache.poi.ss.usermodel.*;7

8

9 public class ReadExcel extendsExcelOperating {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> excelList = re.readExcel(load, "登錄");17 //System.out.println("從excel讀取數據并開始使用:");18 //for (Map list : excelList) {19 //System.out.println(list);20 //for (Map.Entry entry : list.entrySet()) {21 //System.out.println(entry.getValue());22 //}23 //System.out.println();24 //}25

26 //方式二: 讀取單個文件,單行數據27 //Map stringStringMap = re.singleReadXlsx(load, "登錄", 2);28 //System.out.println(stringStringMap);29 //for(Map.Entry entry : stringStringMap.entrySet()){30 //System.out.print("Key = "+entry.getKey()+",value="+entry.getValue() + "\n");31 //}32

33 //方式三: 讀取全部sheet的數據34 //List> lists = re.wholeReadXlsx(load);35 //for (Map i : lists) {36 //System.out.print(i);37 //}38

39 //}

40

41 /**

42 * 通過Workbook來讀取excle表格上的數據43 *44 *@paramload 文件所在路徑45 *@return獲取到的數據46 */

47 public List>wholeReadXlsx(String load) {48 //excel中第幾列 : 對應的表頭

49 Map colAndNameMap = new HashMap();50 List> resultList = new ArrayList>();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 nameAndValMap = new HashMap();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 returnresultList;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 *@paramload 文件所在路徑97 *@paramsheetName sheet表格名字98 *@paramrowNum 指定行數99 *@return找到的全部數據100 */

101 public Map singleReadXlsx(String load, String sheetName, introwNum) {102 Workbook xssfWorkbook =distinguishWorkbook(load);103 Map aMap = new HashMap();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 returnaMap;130 }131

132

133 /**

134 * 指定表格中行的數據長度135 *@paramload 文件名136 *@paramnameSheet 表格名字137 *@return表格行的總數138 */

139 public intsingleXlsx(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 returnrow;147

148 }149

150 /**

151 * 讀取Excel文件中指定sheet的內容152 *153 *@paramload excel文件的所在路徑154 *@paramsheetName sheet名字155 *@return以List返回excel中內容156 */

157 public List>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> list = new ArrayList>();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 map = new LinkedHashMap();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 returnlist;200 }201

202 /**

203 * 把一個Map中的所有鍵和值分別放到一個list中,204 * 再把這兩個list整個放到一個大的list里面,即 [ [key1,key2,key3...] , [value1,value2,value3...] ]205 *206 *@parammap 需要轉換的map207 *@return已轉換后的list208 */

209 public static ListconvertMapToList(Map map) {210 List list = new ArrayList();211 List key_list = new LinkedList();212 List value_list = new LinkedList();213

214 Set set =map.entrySet();215 Iterator> iter1 =set.iterator();216 while(iter1.hasNext()) {217 key_list.add(iter1.next().getKey());218 }219 list.add(key_list);220

221 Collection value =map.values();222 Iterator iter2 =value.iterator();223 while(iter2.hasNext()) {224 value_list.add(iter2.next());225 }226 list.add(value_list);227 returnlist;228 }229 }

WriteExcel寫法如下:很少使用這個類

packagetoolskit.documents;import java.io.*;importjava.util.List;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.usermodel.XSSFCell;importorg.apache.poi.xssf.usermodel.XSSFRow;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;public class WriteExcel extendsExcelOperating{//當前文件已經存在

private String excelPath = "E:/MyFirstExcel.xlsx";//從第幾行插入進去

private intinsertStartPointer;//根據工作薄名進行插入

privateString sheetName;//根據工作薄所在位置進行插入

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

}publicWriteExcel() {

}/*** 總的入口方法*/

public static voidmain(String[] args){

WriteExcel crt= newWriteExcel();int i = new ReadExcel().singleXlsx(crt.excelPath, "sheet");

crt.insertStartPointer= i + 1;

crt.insertRows();

}/*** 在已有的Excel文件中插入一行新的數據的入口方法*/

public voidinsertRows() {

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);

}/*** 保存工作薄

*

*@paramwb*/

private voidsaveExcel(Workbook wb) {

FileOutputStream fileOut;try{

fileOut= newFileOutputStream(excelPath);

wb.write(fileOut);

fileOut.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}/*** 創建要出入的行中單元格

*

*@paramrow

*@return

*/

privateCell 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");returncell;

}/*** 得到一個已有的工作薄的POI對象

*

*@return

*/

privateWorkbook returnWorkBookGivenFileHandle() {

Workbook wb= null;

File f= newFile(excelPath);try{if (f != null) {

wb=distinguishWorkbook(excelPath);

}

}catch(Exception e) {return null;

}returnwb;

}/*** 找到需要插入的行數,并新建一個POI的row對象

*

*@paramsheet

*@paramrowIndex

*@return

*/

privateRow 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);returnrow;

}/*** 把內容寫入Excel

*

*@paramlist 傳入要寫的內容,此處以一個List內容為例,先把要寫的內容放到一個list中

*@paramoutputStream 把輸出流懟到要寫入的Excel上,準備往里面寫數據*/

public void writeExcel(Listlist, OutputStream outputStream) {//創建工作簿

XSSFWorkbook xssfWorkbook;

xssfWorkbook= newXSSFWorkbook();//創建工作表

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輸出的模板:

packagetoolskit;importjava.util.Iterator;importjava.util.List;importjava.util.Map;/*** @ ClassName: SystemOut

* @ Author: DingDong

* @ Date: 2019/8/13 11:33

* @ Version: 1.0

* @ desc:*/

public classSystemOut {public static voidtextStringOut(String data, String text) {

System.out.println(data+ ":" +text);

}public static voidtextStringOut(String status, String data, String text) {

System.out.println(status+ ":" + data + ":" +text);

}public static voidtextStringOut(String text) {

System.out.println(text);

}/*** 用例成功,并且編輯成功

*

*@parammassage 用例編號

*@paramparameter 用例輸入的內容*/

public static voidcaseSuccess(String massage, String parameter) {

System.out.println(massage+ "用例執行成功,編輯內容為:" +parameter);

}/*** 編輯判斷成功

*

*@parammassage 執行編號*/

public static voidcaseEditSuccess(String massage) {

System.out.println(massage+ "用例中的元素對象不需要編輯,程序判斷成功。。");

}/*** 用例執行成功

*

*@parammassage*/

public static voidcaseSuccess(String massage) {

System.out.println(massage+ "用例執行成功");

}/*** 用例執行失敗,并且打印出輸入信息

*

*@parammassage*/

public static voidcaseFail(String massage) {

System.out.println(massage+ "用例執行失敗。。。。");

}/*** 不需要進行編輯時發生失敗

*

*@parammassage 用例編號*/

public static voidcaseEditFail(String massage) {

System.out.println(massage+ "用例中的元素對象不需要編輯,程序判斷失敗。");

}public static voidcaseFail(String massage, String parameter) {

System.out.println(massage+ "用例執行失敗,編輯內容為:" +parameter);

}/***@paramli*/

public static void getStringOut(List li) throwsInterruptedException {

textStringOut("打印list開始" +li.size());for (int i = 0; i < li.size(); i++) {

textStringOut(li.get(i).toString());

}

}public static void getStringOut(Map aMap) throwsInterruptedException {

textStringOut("打印list開始" +aMap.size());

Iterator> iterator =aMap.entrySet().iterator();while(iterator.hasNext()) {

Map.Entry 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

commons-logging

commons-logging

1.2

log4j

log4j

1.2.17

log代碼:

packagetoolskit;importorg.apache.log4j.Logger;/*** @ ClassName: InformationLog

* @ Author: DingDong

* @ Date: 2019/8/9 17:39

* @ Version: 1.0

* @ desc:*/

public classInformationLog {protected static final Logger logger = Logger.getLogger(InformationLog.class);public static voidinputLogInfo(String infoData) {

logger.info(infoData);

}public static voidinputLogDebug(String infoData) {

logger.debug(infoData);

}public static voidinputLogWarn(String infoData) {

logger.warn(infoData);

}public static voidinputLogError(String infoData) {

logger.error(infoData);

}public static voidinputLogFatal(String infoData) {

logger.fatal(infoData);

}

}

說明:

定義文件地址的時候,都是寫死;文件地址這邊寫死(動態又高級的寫法不懂如何編寫)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/533934.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/533934.shtml
英文地址,請注明出處:http://en.pswp.cn/news/533934.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python字符串前面加f什么意思_Python 字符串前面加u,r,b,f的含義

1、字符串前加 u例&#xff1a;u"我是含有中文字符組成的字符串。"作用&#xff1a;后面字符串以 Unicode 格式 進行編碼&#xff0c;一般用在中文字符串前面&#xff0c;防止因為源碼儲存格式問題&#xff0c;導致再次使用時出現亂碼。2、字符串前加 r例&#xff1a…

mysql居左查詢abcd_MySql速查手冊

索引定義索引用來快速地尋找那些具有特定值的記錄&#xff0c;所有MySQL索引都以B樹的形式保存。就像是數據的目錄。索引類型唯一索引主鍵索引B-Tree普通索引R-Tree聯合索引Hash全文索引FullText在mysql中fulltext索引只針對myisam生效。符合索引對于創建的多列索引(復合索引)&…

和python哪個容易胖_為什么有些人特別容易胖?

7種人&#xff0c;最容易被肥胖盯上&#xff0c;其中有你嗎&#xff1f;胖&#xff0c;總是來得猝不及防&#xff0c;肥肉也總是不知不覺地長出來……許多胖友對自己的身材老摸不著腦&#xff0c;其實&#xff0c;長胖都是有跡可循的&#xff01;正如下面這7類人&#xff0c;就…

loadrunner 錯誤: 無法找到 java.exe_LoadRunner錯誤及解決方法總結

1. error:missing newline in d:\loadrunner\name.dat場景執行時報error:missing newline in d:\loadrunner\name.dat第二次執行不報兩個解決辦法&#xff1a;第一&#xff1a;如果參數不是很多的話&#xff0c;不要打開記事本去編輯參數&#xff0c;就直接在LR提供的參數的表格…

gif透明背景動畫_【超實用干貨! 】iPad上的動畫App大推薦

作者/立夏編輯/彼方大家好&#xff0c;我是立夏。大概在兩年前吧我為大家寫過幾款動畫APP的評測&#xff0c;這一次我也想給大家推薦一些我的新寵&#xff0c;供大家參考。我在這里就不過多提及如Animation Desk、Procreate或是Callipeg之類知名度相對更高一些的動畫App了&…

python框架是干什么的_django框架是干什么的

django(Python Web 框架)Django是一個開放源代碼的Web應用框架&#xff0c;由Python寫成。采用了MTV的框架模式&#xff0c;即模型M&#xff0c;視圖V和模版T。它最初是被開發來用于管理勞倫斯出版集團旗下的一些以新聞內容為主的網站的&#xff0c;即是CMS(內容管理系統)軟件。…

iphone如何信任軟件_【手機軟件】千禾影院:全新觀影神器,支持安卓+iOS,最新、最全、高清、免費!...

Hello,大家好&#xff0c;我是春哥&#xff01;每天記得打卡哦&#xff01;感謝每一位小伙伴們的關注和支持&#xff01;免責聲明大部分資源來源于網絡&#xff0c;僅供學習和交流使用&#xff0c;如有侵權請聯系我們刪除。每期文章末尾都會有關鍵詞&#xff0c;在公眾號發消息…

Java小魔女芭芭拉_沉迷蘑菇不可自拔,黏土人《小魔女學園》蘇西·曼芭芭拉 圖賞...

GOOD SMILE出品的黏土人系列手辦新作——《小魔女學園》蘇西曼芭芭拉&#xff0c;已經開始接受預定了。這款黏土人的原型師是來自中國上海的陳天&#xff0c;售價4167日元&#xff0c;預計2018年4月發售。蘇西是主人公亞可的室友&#xff0c;她是從東南亞來的身份不明的魔女。熱…

java int相除向上取整_java實戰項目常用類,Date、Calendar、BigDecimal、Math、UUID

Java開發中經常用到的類和方法&#xff0c;以下主要就日期是時間處理、金融數字處理、數學計算、隨機數、MD5加密等。java.util.Date類java.util 包提供了 Date 類來封裝當前的日期和時間。 Date 類提供兩個構造函數來實例化 Date 對象。日期時間的本質是一個long&#xff0c;它…

python四級中考有用的_一位中考生家長的后悔藥:考前30多天,千萬別做這7件傻事...

中考即將來臨&#xff0c;考后必定是幾家歡樂幾家愁&#xff0c;有慶幸的、有后悔的。中考前的幾個月到底應該怎么過?考前考中需要注意什么&#xff1f;家長做哪些事情是畫蛇添足的。今天給大家推薦一位“中考失敗”學子父親的自白&#xff0c;其中有對優秀兒子的心疼&#xf…

R語言中dim函數_R語言--向量化計算(apply族函數)

R語言最優秀的是它的向量化編程&#xff0c;這其中apply族函數扮演了非常重要的角色。apply族函數是由apply、sapply、lapply、mapply、tapply等函數組成的。熟練使用apply族函數&#xff0c;能夠簡化程序&#xff0c;提高代碼的運算速度。軟件&環境win10 64bitR 3.6.1appl…

php+mysql記事本_一個簡單記事本php操作mysql輔助類創建

//SqlHelper.class.phpconnmysql_connect($this->host,$this->user,$this->passwrd); if(!$this->conn){ die("連接失敗".mysql_error()); } mysql_select_db($this->db); mysql_query("set names utf8"); } //增刪改 function execute_dml…

python init方法做了什么_Python類方法、__new__方法和__init__方法分別是什么

Python類方法、__new__方法和__init__方法分別是什么發布時間&#xff1a;2020-09-03 15:24:06來源&#xff1a;億速云閱讀&#xff1a;104作者&#xff1a;小新這篇文章主要介紹Python類方法、__new__方法和__init__方法分別是什么&#xff0c;文中介紹的非常詳細&#xff0c;…

谷歌瀏覽器中文版_中國科學家設計超薄指尖傳感器,厚度不到A4紙五分之一 / 谷歌發布地圖時光機:百年前,你家街道啥樣?/ AI看圖說話首超人類...

關注我們了解計算機視覺最新動態 &#xff01;動態先覽1中國科學家設計超薄指尖傳感器&#xff0c;厚度不到A4紙五分之一2谷歌發布地圖「時光機」&#xff1a;100年前&#xff0c;你家街道長啥樣&#xff1f;3仿真環境跟車2分鐘&#xff0c;就讓自動駕駛系統撞上馬路牙子&#…

300小時成為java程序員_直擊面試現場: Java程序員3輪6小時面試, 成功拿到阿里offer!...

原標題&#xff1a;直擊面試現場: Java程序員3輪6小時面試, 成功拿到阿里offer!今天給大家分享一位Java程序員小伙去阿里應聘的經歷&#xff01;從Java開發要掌握的技術來講&#xff0c;前面已經說得差不多了。我主要想從面試者的角度談一談看法。如果是我面試&#xff0c;就給…

python 判斷每月最后一天_python獲取某年中每個月的第一天和最后一天的兩種方法...

搜索關鍵字&#xff1a;python get every first day of month參考解答&#xff1a;方法一&#xff1a;>>> import calendar>>> calendar.monthrange(2002,1)(1, 31)>>> calendar.monthrange(2008,2)(4, 29)>>> calendar.monthrange(2100,2…

anaconda python3.8目錄_MacBook Pro 安裝anaconda、配置環境

新入手了MacBook Pro&#xff0c;iOS系統還不算非常熟練...作為一個新手程序員&#xff0c;在python開發道路上的學習就從安裝環境開始吧&#xff1a;1、下載安裝包2、安裝過程一路同意or繼續...不過&#xff0c;mac上彈出不允許在當前路徑安裝&#xff0c;那么選擇自定義安裝路…

中國網建java發送短信_短信驗證登陸-中國網建提供的SMS短信平臺

一、JAVA發送手機短信常見的有三種方式(如下所列)&#xff1a;使用webservice接口發送手機短信,這個可以使用sina提供的webservice進行發送,但是需要進行注冊使用短信mao的方式進行短信的發送,這種方式應該是比較的常用,前提是需要購買硬件設備。二、一下整理了SMS短信驗證過程…

stm32外部中斷_STM32學習筆記 | 電源管理及低功耗設計要點

一款好的電子產品&#xff0c;都需要認真考慮電源管理的問題&#xff0c;電池供電的產品更應該注意低功耗的實現。 STM32電源介紹嵌入式開發直播課 - STM32 USART串口的應用 - 創客學院直播室?www.makeru.com.cn每一塊STM32芯片中都有一個電源控制器&#xff08;PWR&#xff0…

delphi 調用瀏覽器內核_HFL:基于混合模糊測試的Linux內核漏洞挖掘

RemarksConference: NDSS 2020Full Paper: HFL: Hybrid Fuzzing on the Linux KernelSummary針對的問題&#xff1a; Linux 操作系統內核安全漏洞的發現需要新技術。現有解決方案的不足&#xff1a;當前的模糊測試技術難以直接應用于內核安全漏洞發現。提出的創新方案概述&…