遍历项目文件夹下的所有文件

packagecom.huawei.test;

importjava.io.File;

importjava.io.FileOutputStream;

importjava.util.List;

importorg.dom4j.Document;

importorg.dom4j.DocumentHelper;

importorg.dom4j.Element;

importorg.dom4j.io.OutputFormat;

importorg.dom4j.io.SAXReader;

publicclassInsertElement{

/**

*@paramargs

*@throwsException

*/

publicstaticvoidmain(String[]args)throwsException{

//递归项目文件夹下的所有文件夹及其中文件

Fileroot=newFile("E:\\eclipse3.6space\\Task");

showAllFiles(root);

}

finalstaticvoidshowAllFiles(Filedir)throwsException{

File[]fs=dir.listFiles();

for(inti=0;i<fs.length;i++){

if(fs[i].getAbsolutePath().contains("strings.xml")

&&!fs[i].getAbsolutePath().contains("large")){

System.out.println(fs[i].getAbsolutePath());

}

if(fs[i].isDirectory()){

try{

showAllFiles(fs[i]);

}catch(Exceptione){}

}

}

try{

OutputFormatformat=OutputFormat.createPrettyPrint();

format.setEncoding("utf-8");

SAXReaderreader=newSAXReader();

Documentdocument=reader.read("C:\\Users\\Administrator\\Desktop\\strings.xml");

Elementroot=document.getRootElement();

List<Element>elements=root.elements();

intindex=0;

for(Elementelement:elements){

index++;

if("app_name".equals(element.attributeValue("name"))){

Elementelem=DocumentHelper.createElement("string");

elem.addAttribute("name","bbb");

elem.setText("ppppppp");

//elem.addAttribute("name","ccc");

elements.add(index,elem);

break;

}

}

OutputFormatformat1=OutputFormat.createPrettyPrint();//缩减型格式

//OutputFormatformat=OutputFormat.createCompactFormat();//紧凑型格式

format1.setEncoding("utf-8");//设置编码

////format.setTrimText(false);//设置text中是否要删除其中多余的空格

org.dom4j.io.XMLWriterxmlWriter=neworg.dom4j.io.XMLWriter(

newFileOutputStream(newFile("C:\\Users\\Administrator\\Desktop\\strings.xml")),format1);

//XMLWriterwriter=newXMLWriter(newFileWriter("C:\\Users\\Administrator\\Desktop\\strings.xml"),format);

xmlWriter.write(document);

xmlWriter.close();

}catch(Exceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

}

}

相关推荐