SpringBoot框架如何管理Xml和CSV
XML是可擴展標記語言,是一種用于標記電子文件使其具有結構性的標記語言。標記指計算機所能理解的信息符號,通過此種標記,計算機之間可以處理包含各種的信息比如數據結構,格式等。它可以用來標記數據、定義數據類型,是一種允許用戶對自己的標記語言進行定義的源語言。適合網絡傳輸,提供統一的方法來描述和交換應用程序的結構化數據。
2、CSV文檔CSV文檔,以逗號分隔文檔內容值,其文件以純文本形式存儲結構數據。CSV文件由任意數目的記錄組成,記錄間以某種換行符分隔;每條記錄由字段組成,字段間的分隔符是其它字符或字符串,最常見的是逗號。CSV是一種通用的、相對簡單的文件格式,通常被用在大數據領域,進行大規模的數據搬運操作。
二、XML文件管理1、Dom4j依賴Dom4j是基于Java編寫的XML文件操作的API包,用來讀寫XML文件。具有性能優異、功能強大和簡單易使用的特點。
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version></dependency><dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1.6</version></dependency>2、基于API封裝方法
涉及對XML文件讀取、加載、遍歷、創建、修改、刪除等常用方法。
public class XmlUtil { /** * 創建文檔 */ public static Document getDocument (String filename) {File xmlFile = new File(filename) ;Document document = null;if (xmlFile.exists()){ try{SAXReader saxReader = new SAXReader();document = saxReader.read(xmlFile); } catch (Exception e){e.printStackTrace(); }}return document ; } /** * 遍歷根節點 */ public static Document iteratorNode (String filename) {Document document = getDocument(filename) ;if (document != null) { Element root = document.getRootElement(); Iterator iterator = root.elementIterator() ; while (iterator.hasNext()) {Element element = (Element) iterator.next();System.out.println(element.getName()); }}return document ; } /** * 創建XML文檔 */ public static void createXML (String filePath) throws Exception {// 創建 Document 對象Document document = DocumentHelper.createDocument();// 創建節點,首個節點默認為根節點Element rootElement = document.addElement('project');Element parentElement = rootElement.addElement('parent');parentElement.addComment('版本描述') ;Element groupIdElement = parentElement.addElement('groupId') ;Element artifactIdElement = parentElement.addElement('artifactId') ;Element versionElement = parentElement.addElement('version') ;groupIdElement.setText('SpringBoot2');artifactIdElement.setText('spring-boot-starters');versionElement.setText('2.1.3.RELEASE');//設置輸出編碼OutputFormat format = OutputFormat.createPrettyPrint();File xmlFile = new File(filePath);format.setEncoding('UTF-8');XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFile),format);writer.write(document);writer.close(); } /** * 更新節點 */ public static void updateXML (String filePath) throws Exception {Document document = getDocument (filePath) ;if (document != null){ // 修改指定節點 List elementList = document.selectNodes('/project/parent/groupId'); Iterator iterator = elementList.iterator() ; while (iterator.hasNext()){Element element = (Element) iterator.next() ;element.setText('spring-boot-2'); } //設置輸出編碼 OutputFormat format = OutputFormat.createPrettyPrint(); File xmlFile = new File(filePath); format.setEncoding('UTF-8'); XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFile),format); writer.write(document); writer.close();} } /** * 刪除節點 */ public static void removeElement (String filePath) throws Exception {Document document = getDocument (filePath) ;if (document != null){ // 修改指定節點 List elementList = document.selectNodes('/project/parent'); Iterator iterator = elementList.iterator() ; while (iterator.hasNext()){Element parentElement = (Element) iterator.next() ;Iterator parentIterator = parentElement.elementIterator() ;while (parentIterator.hasNext()){ Element childElement = (Element)parentIterator.next() ; if (childElement.getName().equals('version')) {parentElement.remove(childElement) ; }} } //設置輸出編碼 OutputFormat format = OutputFormat.createPrettyPrint(); File xmlFile = new File(filePath); format.setEncoding('UTF-8'); XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFile),format); writer.write(document); writer.close();} } public static void main(String[] args) throws Exception {String filePath = 'F:file-typeproject-cf.xml' ;// 1、創建文檔Document document = getDocument(filePath) ;System.out.println(document.getRootElement().getName());// 2、根節點遍歷iteratorNode(filePath);// 3、創建XML文件String newFile = 'F:file-typeproject-cf-new.xml' ;createXML(newFile) ;// 4、更新XML文件updateXML(newFile) ;// 5、刪除節點removeElement(newFile) ; }}3、執行效果圖
這里不需要依賴特定的Jar包,按照普通的文件讀取即可。
2、文件讀取@Async@Overridepublic void readNotify(String path, Integer columnSize) throws Exception { File file = new File(path) ; String fileName = file.getName() ; int lineNum = 0 ; if (fileName.startsWith('data-')) {InputStreamReader isr = new InputStreamReader(new FileInputStream(file),'GBK') ;BufferedReader reader = new BufferedReader(isr);List<DataInfo> dataInfoList = new ArrayList<>(4);String line ;while ((line = reader.readLine()) != null) { lineNum ++ ; String[] dataArray = line.split(','); if (dataArray.length == columnSize) {String cityName = new String(dataArray[1].getBytes(),'UTF-8') ;dataInfoList.add(new DataInfo(Integer.parseInt(dataArray[0]),cityName,dataArray[2])) ; } if (dataInfoList.size() >= 4){LOGGER.info('容器數據:'+dataInfoList);dataInfoList.clear(); }}if (dataInfoList.size()>0){ LOGGER.info('最后數據:'+dataInfoList);}reader.close(); } LOGGER.info('讀取數據條數:'+lineNum);}3、文件創建
@Async@Overridepublic void createCsv(List<String> dataList,String path) throws Exception { File file = new File(path) ; boolean createFile = false ; if (file.exists()){boolean deleteFile = file.delete() ;LOGGER.info('deleteFile:'+deleteFile); } createFile = file.createNewFile() ; OutputStreamWriter ost = new OutputStreamWriter(new FileOutputStream(path),'UTF-8') ; BufferedWriter out = new BufferedWriter(ost); if (createFile){for (String line:dataList){ if (!StringUtils.isEmpty(line)){out.write(line);out.newLine(); }} } out.close();}4、編寫測試接口
這里基于Swagger2管理接口測試 。
@Api('Csv接口管理')@RestControllerpublic class CsvWeb { @Resource private CsvService csvService ; @ApiOperation(value='文件讀取') @GetMapping('/csv/readNotify') public String readNotify (@RequestParam('path') String path, @RequestParam('column') Integer columnSize) throws Exception {csvService.readNotify(path,columnSize);return 'success' ; } @ApiOperation(value='創建文件') @GetMapping('/csv/createCsv') public String createCsv (@RequestParam('path') String path) throws Exception {List<String> dataList = new ArrayList<>() ;dataList.add('1,北京,beijing') ;dataList.add('2,上海,shanghai') ;dataList.add('3,蘇州,suzhou') ;csvService.createCsv(dataList,path);return 'success' ; }}四、源代碼地址
文中涉及文件類型,在該章節源碼ware18-file-parent/case-file-type目錄下。
GitHub·地址https://github.com/cicadasmile/middle-ware-parentGitEE·地址https://gitee.com/cicadasmile/middle-ware-parent
以上就是SpringBoot框架如何管理Xml和CSV的詳細內容,更多關于SpringBoot管理Xml和CSV的資料請關注好吧啦網其它相關文章!
相關文章:
