动态生成seo目录 (三)

38 篇文章 0 订阅
10 篇文章 0 订阅

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文件转换成jsonobejc
            JSONObject 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();// 当前节点的所有属性的list
        for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
            result.put(attr.getName(), attr.getValue());
        }
        // 递归遍历当前节点所有的子节点
        List<Element> listElement = node.elements();// 所有一级子节点的list
        if (!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();
            //如果有替换就删除源文件,用新文件替换旧文件,如果没有替换就返回false
            if(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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值