java读取,覆盖,追加txt 内容 (二)包含网络读取

72 篇文章 0 订阅
38 篇文章 0 订阅

直接见代码: 

package com.oce.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

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("UTF-8"));
            fileOutputStream.close();
            flag=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static boolean writeTxtFileTwo(String content,File fileName)throws Exception{
        boolean flag=false;
        try {
            if(content!=null && fileName!=null){
                Writer out =new FileWriter(fileName);
                out.write(content);
                out.close();
                flag=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static String readTxtFileln(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){
                if(s!=null&& !s.equals("")){
                    result = result+s+"\n";
                }
                System.out.println("读取的内容为:"+s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**

     * 写入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\\robotsTxt.txt");
        createFile(file);
        String outText= readTxtFile(file);
        System.out.println(outText);
        OperationTxt.createFile(file);
        boolean t= OperationTxt.writeTxtFile("11111111111111111111111111",file);
        //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("/usr/local/nginx/html/sitemap/sitemap_top.txt","http://www.oceano.com.cn/tyd","http://www.oceano.com.cn/tyd");
        //OperationTxt.outTxt(1,"/usr/local/nginx/html/sitemap/sitemap_index.xml");
    }

    /**
     * 监测更新文件对文件目录更新时间进行刷新
     * @param index
     * @param path
     */
    public static void outTxt(int index,String path,boolean staic){
        if(staic){
            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,boolean staic) {
        if(staic){
            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();
            }
        }
    }

    /**
     * 根据网络路径获取文件内容
     * @param filePath
     * @return
     */
    public static String openFile(String filePath) {
        int HttpResult; // 服务器返回的状态
        String ee = new String();
        try
        {
            URL url =new URL(filePath); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            urlconn.connect();
            HttpURLConnection httpconn =(HttpURLConnection)urlconn;
            HttpResult = httpconn.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("无法连接到");
            } else {
                int filesize = urlconn.getContentLength(); // 取数据长度
                InputStreamReader isReader = new InputStreamReader(urlconn.getInputStream(),"UTF-8");
                BufferedReader reader = new BufferedReader(isReader);
                StringBuffer buffer = new StringBuffer();
                String line; // 用来保存每行读取的内容
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line); // 将读到的内容添加到 buffer 中
                    buffer.append(" "); // 添加换行符
                    line = reader.readLine(); // 读取下一行
                }
                System.out.print(buffer.toString());
                ee = buffer.toString();
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return  ee;
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值