import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class xmlAndJpg {
public static void main(String[] args) throws DocumentException, IOException {
String path = "F:\\testXMLAndJpg\\";
File file = new File(path);
List<String> xml = new ArrayList();
List<String> jpg = new ArrayList();
if (file.isDirectory()){
System.out.println("文件夹");
String[] fileList = file.list();
for (int i = 0; i < fileList.length;i++){
File files = new File(path + "\\" + fileList[i]);
if (files.getName().endsWith(".xml")){
xml.add(firstUtil(files.getName()));
}
if (files.getName().endsWith(".jpg")){
jpg.add(firstUtil(files.getName()));
}
}
}
Document read = null;
for (int j = 0 ; j < jpg.size();j++)
if (!xml.contains(jpg.get(j))) {
File flag = new File(path + jpg.get(j) + ".jpg");
flag.delete();
} else {
File flag1 = new File(path + jpg.get(j) + ".xml");
SAXReader saxReader = new SAXReader();
read = saxReader.read(flag1);
Element rootElement = read.getRootElement();
List<Element> elementList = rootElement.elements();
for (Element element : elementList) {
if (element.getName().equals("filename")) {
System.out.println(element.getText());
element.setText(jpg.get(j));
}
if (element.getName().equals("path")) {
System.out.println(element.getText());
element.setText(path + jpg.get(j) + ".jpg");
}
}
FileOutputStream fileOutputStream = new FileOutputStream(flag1);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "utf-8"));
read.write(bufferedWriter);
bufferedWriter.flush();
bufferedWriter.close();
}
}
public static String firstUtil(String str){
return str.substring(0,str.indexOf("."));
}
}
xml与jpg一对一映射的问题,如果jpg多余那么删了,并且将xml中的filename和path属性换成jpg的文件名和全路径
最新推荐文章于 2023-10-18 10:56:35 发布