1.根据新增数据和修改数据,更新服务器txt文本中的url.
2.更新指向txt文本的时间
当更新对应文本中的url时要更新这里的时间
这里的链接当新增和修改项目中的链接时,这里也对于修改和新增
代码:
package com.oce.util;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;public class OperationTxt {/*** 创建文件* @param fileName* @return*/public static boolean createFile(File fileName)throws Exception{try{System.out.println("判断文件是否存在");if(!fileName.exists()){System.out.println("文件不存在开始创建创建");fileName.createNewFile();}else {System.out.println("文件文件存在准备读取文件");}}catch(Exception e){e.printStackTrace();}return true;}/***读取TXT内容* @param file* @return*/public static String readTxtFile(File file){String result = "";try {InputStreamReader reader = new InputStreamReader(new FileInputStream(file),"gbk");BufferedReader br = new BufferedReader(reader);String s = null;while((s=br.readLine())!=null){result = result + s;System.out.println("读取的内容为:"+s);}} catch (Exception e) {e.printStackTrace();}return result;}/*** 写入TXT,覆盖原内容* @param content* @param fileName* @return* @throws Exception*/public static boolean writeTxtFile(String content,File fileName)throws Exception{RandomAccessFile mm=null;boolean flag=false;FileOutputStream fileOutputStream=null;try {fileOutputStream = new FileOutputStream(fileName);fileOutputStream.write(content.getBytes("gbk"));fileOutputStream.close();flag=true;} catch (Exception e) {e.printStackTrace();}return flag;}/*** 写入TXT,追加写入* @param filePath* @param content*/public static void fileChaseFW(String filePath, String content) {if(content==null || content.equals("")){return;}try {//构造函数中的第二个参数true表示以追加形式写文件FileWriter fw = new FileWriter(filePath,true);fw.write("\r\n");fw.write(content);fw.close();} catch (IOException e) {System.out.println("文件写入失败!" + e);}}public static void main(String[] args) throws Exception{File file = new File("C:\\Users\\hunuo\\Desktop\\dome.xml");createFile(file);String outText= readTxtFile(file);System.out.println(outText);//writeTxtFile("我是写入的内容11",file);//fileChaseFW("C:\\Users\\hunuo\\Desktop\\Operation.txt","66666666");//String outText1= readTxtFile(file);//System.out.println(outText1);
// JSONObject jsonObject=StringAnalysisXml.documentToJSONObject(outText);
// System.out.println("------------------------------------------------------");
// System.out.println(jsonObject);
// JSONArray jsonElements=jsonObject.getJSONArray("sitemap");
// System.out.println(jsonElements);System.out.println("------------------------------------------------------");putSeoUrl("C:\\Users\\hunuo\\Desktop\\sitemap_top.txt","http://www.XXX.cn/xgt","http://www.XXX.com.cn/ybj");OperationTxt.outTxt(0,"C:\\Users\\hunuo\\Desktop\\dome.xml");}/*** 监测更新文件对文件目录更新时间进行刷新* @param index* @param path*/public static void outTxt(int index,String path){SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");try {//读取文件File file = new File(path);//文件不存在就创建createFile(file);//读取文件内容String outText= readTxtFile(file);//将xml文件转换成jsonobejcJSONObject jsonObject=StringAnalysisXml.documentToJSONObject(outText);JSONArray jsonElements=jsonObject.getJSONArray("sitemap");JSONArray jsonArray=new JSONArray();for(int i=0;i<=jsonElements.size()-1;i++){if(i==index){JSONObject text=jsonElements.getJSONObject(index);text.put("lastmod",formatter.format(new Date()));jsonArray.add(text);}else {jsonArray.add(jsonElements.getJSONObject(i));}}System.out.println(jsonArray);jsonObject.put("sitemap",jsonArray);//把文件内容写入文本中//writeTxtFile("123",file);StringBuffer buffer = new StringBuffer();buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n");buffer.append("<sitemapindex>\n");String xml=StringAnalysisXml.jsonToXmlstr(jsonObject,buffer);writeTxtFile(xml+"</sitemapindex>",file);}catch (Exception e){e.printStackTrace();}}/*** 将更新的内容替换的对应的服务器文本上(若文本上有就进行替换,没有就追加)* @param path*/public static void putSeoUrl(String path,String oldString,String newString) {try {File file = new File(path);createFile(file);//建立临时文件路径String url=path.replaceAll(path.substring(path.lastIndexOf("/")+1),"") ;String urlPth=url+System.currentTimeMillis()+".txt";//判断文本中是否包含该文件,若包含就进行替换boolean t= StringAnalysisXml.alterStringToCreateNewFile(oldString,newString,urlPth,file);//判断是否替换,若没有就添加内容if(t==false){if(newString!=null && !newString.equals("")){fileChaseFW(path,newString);}}}catch (Exception e){e.printStackTrace();}}
}
和XML相关的方法:
package com.oce.util;import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;public class StringAnalysisXml {/*** String 转 org.dom4j.Document* @param xml* @return* @throws DocumentException*/public static Document strToDocument(String xml){try {//加上xml标签是为了获取最外层的标签,如果不需要可以去掉return DocumentHelper.parseText(xml);} catch (DocumentException e) {return null;}}/*** org.dom4j.Document 转 com.alibaba.fastjson.JSONObject* @param xml* @return* @throws DocumentException*/public static JSONObject documentToJSONObject(String xml){return elementToJSONObject(strToDocument(xml).getRootElement());}/*** org.dom4j.Element 转 com.alibaba.fastjson.JSONObject* @param node* @return*/public static JSONObject elementToJSONObject(Element node) {JSONObject result = new JSONObject();// 当前节点的名称、文本内容和属性List<Attribute> listAttr = node.attributes();// 当前节点的所有属性的listfor (Attribute attr : listAttr) {// 遍历当前节点的所有属性result.put(attr.getName(), attr.getValue());}// 递归遍历当前节点所有的子节点List<Element> listElement = node.elements();// 所有一级子节点的listif (!listElement.isEmpty()) {for (Element e : listElement) {// 遍历所有一级子节点if (e.attributes().isEmpty() && e.elements().isEmpty()) // 判断一级节点是否有属性和子节点result.put(e.getName(), e.getTextTrim());// 沒有则将当前节点作为上级节点的属性对待else {if (!result.containsKey(e.getName())) // 判断父节点是否存在该一级节点名称的属性result.put(e.getName(), new JSONArray());// 没有则创建((JSONArray) result.get(e.getName())).add(elementToJSONObject(e));// 将该一级节点放入该节点名称的属性对应的值中}}}return result;}/*** 将jsonobject 转换成 xml字符串* jobj 数据部分内容,buffer xml 文件标准内容* @param jObj the j obj* @param buffer the buffer* @return the string*/public static String jsonToXmlstr(JSONObject jObj,StringBuffer buffer ){Set<Map.Entry<String, Object>> se = jObj.entrySet();for(Iterator<Map.Entry<String, Object>> it = se.iterator(); it.hasNext(); ){Map.Entry<String, Object> en = it.next();if(en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONObject")){buffer.append(" <"+en.getKey()+">");JSONObject jo = jObj.getJSONObject(en.getKey());jsonToXmlstr(jo,buffer);buffer.append(" </"+en.getKey()+"> \n");}else if(en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONArray")){JSONArray jarray = jObj.getJSONArray(en.getKey());for (int i = 0; i < jarray.size(); i++) {buffer.append(" <"+en.getKey()+">");JSONObject jsonobject = jarray.getJSONObject(i);jsonToXmlstr(jsonobject,buffer);buffer.append("</"+en.getKey()+"> \n");}}else if(en.getValue().getClass().getName().equals("java.lang.String")){buffer.append(" <"+en.getKey()+">"+en.getValue());buffer.append("</"+en.getKey()+"> \n");}}return buffer.toString();}/*** 替换文本内容中的特定的字符串* @param oldString 需要替换的字符串* @param newString 替换的内容* @param path 临时文件的路径* @param file 源文件*/public static boolean alterStringToCreateNewFile( String oldString, String newString ,String path,File file){boolean t=true;try {long start = System.currentTimeMillis(); //开始时间BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream( file))); //创建对目标文件读取流File newFile = new File(path); //创建临时文件if (!newFile.exists()){newFile.createNewFile(); //不存在则创建}//创建对临时文件输出流,并追加BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile,true)));String string = null; //存储对目标文件读取的内容int sum = 0; //替换次数while ((string = br.readLine()) != null){//判断读取的内容是否包含原字符串if (string.contains(oldString)){//替换读取内容中的原字符串为新字符串string = new String(string.replace(oldString,newString));sum++;}bw.write(string);bw.newLine(); //添加换行}br.close(); //关闭流,对文件进行删除等操作需先关闭文件流操作bw.close();String filePath = file.getPath();//如果有替换就删除源文件,用新文件替换旧文件,如果没有替换就返回falseif(sum>0){file.delete(); //删除源文件newFile.renameTo(new File(filePath)); //将新文件更名为源文件}else {newFile.delete();t=false;}long time = System.currentTimeMillis() - start; //整个操作所用时间;System.out.println(sum+"个"+oldString+"替换成"+newString+"耗费时间:"+time);} catch(Exception e){System.out.println(e.getMessage());t=false;}return t;}
}