文件系統(02):基於SpringBoot框架,管理Xml和CSV

  • 2020 年 2 月 17 日
  • 筆記

一、文檔類型簡介

1、XML文檔

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-type\project-cf.xml" ;          // 1、創建文檔          Document document = getDocument(filePath) ;          System.out.println(document.getRootElement().getName());          // 2、根節點遍歷          iteratorNode(filePath);          // 3、創建XML文件          String newFile = "F:\file-type\project-cf-new.xml" ;          createXML(newFile) ;          // 4、更新XML文件          updateXML(newFile) ;          // 5、刪除節點          removeElement(newFile) ;      }  }  

3、執行效果圖

三、CSV文件管理

1、CSV文件樣式

這裡不需要依賴特定的Jar包,按照普通的文件讀取即可。

2、文件讀取

@Async  @Override  public 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  @Override  public 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接口管理")  @RestController  public 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-parent  GitEE·地址  https://gitee.com/cicadasmile/middle-ware-parent