java读写文件和字符串操作

来源:互联网 发布:caliber中文软件 编辑:程序博客网 时间:2024/06/18 10:17
package com.xml;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;

public class RardFile {
    public static void main(String[] args) {
        //readFile();
        //System.out.print(readFile());
        //writFile("127.0.0.1,11.93.204");
        //System.out.println(checkIP("127.0.0.1"));
        //toString("127.0.0.1 11.93.204");
        //System.out.println(str_replace(" ",",","21.2.1.21 127.0.0.1 1.93.204"));
    }
    /**
     * 读文件
     * @return
     */
    public static String readFile(){
        FileReader fr;
        StringBuilder sb = new StringBuilder();
        //String str;
        try {
            fr = new FileReader("src/TSCIRatingIP.txt");
            int ch = 0;  
            while((ch = fr.read())!=-1 )  
            {  
            sb.append((char)ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    /**
     * 写文件
     * @param str
     */
    public static void writFile(String str){
        //String str;
        try {
            FileWriter fw = new FileWriter("src/TSCIRatingIP.txt");
            String s;
            if(str!=null && !str.trim().equals("")){
                s = str;
            }else{
                s = "127.0.0.1";
            }
            fw.write(s,0,s.length());  
            fw.flush();  
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 空格分割符
     */
    public static String toString(String str){
        String[] sa = null;
        try {
            sa = str.split(" ");
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (String string : sa) {
            System.out.println(string);
        }
        return "";
    }
    /**
     * 校验合法性
     * @param ip
     * @return
     */
    public static boolean checkIP(String ip){
        boolean b=false;
        String[] sa = ip.split(",");
        for (String string : sa) {
            if(ip.indexOf(string)!=-1){
                b=true;
                return b;
            }
        }
        return b;
    }
    
       /**
        *   字符串替换函数
        *   @param   from   要替换的字符
        *   @param   to   要替换成的目标字符
        *   @param   source   要替换的字符串
        *   @return   替换后的字符串
        */
        public static String str_replace(String from,String to,String source)   {
            StringBuffer   bf=   new   StringBuffer( " ");
            StringTokenizer   st   =   new   StringTokenizer(source,from,true);
            while   (st.hasMoreTokens())   {
                String   tmp   =   st.nextToken();
                if(tmp.equals(from))   {
                    bf.append(to);
                }   else   {
                    bf.append(tmp);
                }
            }
            return   bf.toString();
        }
}


原创粉丝点击