本文源碼: GitHub·點這裡 || GitEE·點這裡
一、文檔類型簡介
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