java讀取,覆蓋,追加txt 內容 (二)包含網絡讀取

直接見代碼: 

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;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章