JAVA常用工具类

总结的JAVA开发常用的工具类

一、获取本机IP和MAC地址

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * 获取本机IP和MAC地址的工具类
 * 
 * @author CHX
 *
 */
public class LocalIPAndMAC {
    /**
     * 获取mac地址的方法
     * 
     * @param ia
     *            InetAddress对象
     * @return mac地址
     * @throws SocketException
     */
    private static String getLocalMac(InetAddress ia) throws SocketException {
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        StringBuffer sb = new StringBuffer("");

        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            int temp = mac[i] & 0xff;
            String str = Integer.toHexString(temp);
            if (str.length() == 1) {
                sb.append("0" + str);
            } else {
                sb.append(str);
            }
        }

        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) {
        try {
            System.out.println("本机IP为  :" + getMyIP());
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        }
        try {
            System.out.println("本机mac地址为 :" + getLocalMac(InetAddress.getLocalHost()));
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取本机IP地址的方法
     * 
     * @return ip地址
     * @throws UnknownHostException
     */
    public static String getMyIP() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }
}

 也可以直接使用InetAddress.getLocalHost().getHostAddress()

二、简易版JAVA生成固定四位短连接

前言:利用base64与md5,生成定长四位的短连接(不包括域名)。本程序和网上的大多数都不同,如果有不对的地方希望能够指出。

举例:http://Nolog/asdasdasd/asdasda/aqwertyuiopasdfghjklzxcvbnm5132456789

效果:

代码:

package com.kh.pds.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 短网址的实现,不管多长,都生成四位链接
 *
 * @author CHX
 */

public class ShortURL {

    private static String plainUrl = "http://Nolog/asdasdasd/asdasda/aqwertyuiopasdfghjklzxcvbnm5132456789";

    private static String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"};

    public static void main(String[] args) {
        myTestShort(plainUrl, "Nolog");
    }

    /**
     * 首先从URL中获取固定格式后的内容
     *
     * @param longUrl 原url
     * @param yuMing  域名
     */
    public static void myTestShort(String longUrl, String yuMing) {

        String regex = "(http://|https://)" + yuMing + "(.*)";

        Pattern r = Pattern.compile(regex);

// 现在创建 matcher 对象

        Matcher m = r.matcher(longUrl);

        if (m.find()) {

            String url = m.group(2);

            if (url != null) {

// 此处就是生成的四位短连接

                System.out.println(m.group(1) + yuMing + "/" + changes(url));

            }

        }

    }

    /**
     * 编码思路:考虑到base64编码后,url中只有[0-9][a-z][A-Z]这几种字符,所有字符共有26+26+10=62种 对应的映射表为62进制即可
     *
     * @param value
     * @return
     */
    public static String changes(String value) {

// 获取base64编码

        String stringBase64 = stringBase64(value);

// 去除最后的==(这是base64的特征,最后以==结尾)

        stringBase64 = stringBase64.substring(0, stringBase64.length() - 2);

        MessageDigest md5 = null;

        try {

            md5 = MessageDigest.getInstance("MD5");

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        }

// 利用md5生成32位固长字符串

        String mid = new String(bytesToHexString(md5.digest(stringBase64.getBytes())));

        StringBuilder outChars = new StringBuilder();

        for (int i = 0; i < 4; i++) {

//每八个一组

            String sTempSubString = mid.substring(i * 8, i * 8 + 8);

// 想办法将此16进制的八个字符数缩减到62以内,所以取余,然后置换为对应的字母数字

            outChars.append(chars[(int) (Long.parseLong(sTempSubString, 16) % chars.length)]);

        }

        return outChars.toString();
    }

    /**
     * 将字符串转换为base64编码
     *
     * @param text 原文
     * @return
     */
    public static String stringBase64(String text) {
        return Base64.getEncoder().encodeToString(text.getBytes());
    }

    /**
     * 将byte转换为16进制的字符串
     *
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}

 三、获取指定类的绝对路径

    /**
     * 获取指定类的绝对路径
     * 
     * @param c
     * @return
     */
    public static String getNowClassPath(Class<?> c) {
        return c.getResource("").getPath().replaceFirst("/", "");
    }

 四、通过JAVA反射机制生成指定XML

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class xmlUtil{

/**
     * 根据传入obj创建请求的xml
     * 
     * @param obj
     *            待生成的obj
     * @param header
     *            待生成的头公共域
     * @return Document
     * @throws Exception
     */
    public Document createXmlObjectReq(Object obj, Object header, boolean ifBody) throws Exception {
        // 创建公共域
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder doc = documentFactory.newDocumentBuilder();
        Document root = doc.newDocument();

        // 添加固定标签
        Element transaction = root.createElement("Transaction");
        Element transaction_Header = root.createElement("Transaction_Header");
        Class<? extends Object> headClass = header.getClass();
        Field[] headFields = headClass.getDeclaredFields();

        for (int i = 0; i < headFields.length; i++) {
            String fieldName = headFields[i].getName();
            String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Method method = headClass.getMethod(methodName, new Class[] {});
            String invoke = (String) method.invoke(header, new Object[] {});
            Element element = root.createElement(fieldName);
            element.setTextContent(invoke);
            transaction_Header.appendChild(element);
        }

        transaction.appendChild(transaction_Header);
        root.appendChild(transaction);

        if (ifBody) {
            // 报文体
            Element Transaction_Body = root.createElement("Transaction_Body");
            // request
            Element request = root.createElement("request");
            Transaction_Body.appendChild(request);

            Class<? extends Object> obcClass = obj.getClass();
            Field[] objFields = obcClass.getDeclaredFields();

            for (int i = 0; i < objFields.length; i++) {
                String fieldName = objFields[i].getName();
                String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Method method = obcClass.getMethod(methodName, new Class[] {});
                String invoke = (String) method.invoke(obj, new Object[] {});
                Element Pyr_BkCgyCd = root.createElement(fieldName);
                Pyr_BkCgyCd.setTextContent(invoke);
                request.appendChild(Pyr_BkCgyCd);
            }

            transaction.appendChild(Transaction_Body);
        }

        return root;
    }

    public String xmlToString(Document root) throws Exception {
        // 创建TransformerFactory对象
        TransformerFactory tff = TransformerFactory.newInstance();
        // 创建 Transformer对象
        Transformer tf = tff.newTransformer();
        tf.setOutputProperty("encoding", JianHangUtil.JH_CHART);
        tf.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        // 去除standalone="no"
        root.setXmlStandalone(true);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        tf.transform(new DOMSource(root), new StreamResult(bos));
        String string = bos.toString();
        bos.close();
        return string;
    }
}

五、生成指定位数(8位以上,且为偶数位)的ID

前排提示:该方法未经过正规测试,用于普通场景没问题(八位数-两千万次无重复)。效率一般,总之慎用。

main方法里是多线程测试,如果有输出,则说明有重复值。

真实使用时,去掉main方法及Runnable

package kh.pms.test;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import kh.pms.tools.StringUtil;

/**
 * 获取指定位数唯一id=生成uuid->加密md5(32位)->生成对应十六进制字符串->每两位一转换最终位数
 * 
 * @author CHX
 * 
 */
public class UniqueIDUtil implements Runnable {
    public static Map<String, String> code = new HashMap<String, String>();
    private static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z" };

    /**
     * 将字符串转换为指定长度字符串
     * 
     * @param value
     * @return
     * @throws Exception
     */
    public String getID(int length) throws Exception {

if (length < 8 || length % 2 != 0) {
return "";
}

        String value = UUID.randomUUID().toString();
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        int bit = 32 / length;
        value = value.replaceAll("-", "");
        value = StringUtil.getBaseStrBian(value.getBytes());
        value = value.replaceAll("=", "");

        byte[] digest = md5.digest(value.getBytes());
        // 利用md5生成32位固长字符串
        String mid = bytesToHexString(digest);
        StringBuilder outChars = new StringBuilder();

        for (int i = 0; i < length; i++) {
            String sTempSubString = mid.substring(i * bit, i * bit + bit);
            outChars.append(chars[(int) (Long.parseLong(sTempSubString, 16) % chars.length)]);
        }

        return outChars.toString();
    }

    /**
     * 将byte转换为16进制的字符串
     * 
     * @param src
     * @return
     */
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            UniqueIDUtil idUtil = new UniqueIDUtil();
            Thread thread = new Thread(idUtil);
            thread.start();
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 100000; i++) {
            String id;
            try {
                id = getID(8);
                synchronized (code) {
                    if (code.containsKey(id)) {
                        System.out.println(id);
                    } else {
                        code.put(id, id);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

六、字符串判空

前排提示:各个第三方jar包都提供字符串判空的方法,如果没有特殊情况请使用成熟的(如hutool)方法。我提供的方法并没有考虑效率及其他问题。

下面的方法特色为:可以输入多个字符串同时判空,并且认为undefined也为空的一种。

    public boolean isNull(String... plains) {
        if (plains == null || plains.length == 0) {
            return true;
        }

        for (int i = 0; i < plains.length; i++) {
            if (plains[i] == null || "".equals(plains[i].trim())
                    || "undefined".toUpperCase().equals(plains[i].toUpperCase())
                    || plains[i].length() == 0) {
                return true;
            }
        }

        return false;
    }

七、获取一个月前的日期(举一反三)

//2.获取前一个月
Calendar startDT = Calendar.getInstance();
startDT.setTime(new Date());
startDT.add(Calendar.DAY_OF_MONTH, -1);

八、有关word操作

   /** 
     * 对请求下载word文件作出回应
     * 
     * @author chx
     * @param document
     * @param response
     * @param fileName  
     * @return   
     */ 
    public static void exportWord(XWPFDocument document, HttpServletResponse response,
                                  String fileName) throws Exception {
        fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        OutputStream os = response.getOutputStream();
        document.write(os);
        os.flush();
        os.close();
    }

本次只介绍poi操作word文档的方法!

maven引入版本号如下:

<poi.version>3.7</poi.version>

maven引入依赖如下:

    <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>${poi.version}</version>
        </dependency>

使用说明:我们的项目是提前准备好word模板,进行文字和图片替换,这要比直接生成word文档方便的多的多!!!如果前提不一致,只能去百度一下别的方法。

其中,文字和图片信息封装进Map里,图片是用Base64编码后的字符串。key值是有区别性的,比如文字以word开头,图片以img开头,这样才能在替换过程中知道是替换文字还是图片。

Map中的key值就是Word文档中的预留替换字。调用generateWord方法即可获取一个word文档,可以传给前端,也可写入文件,自行操作。

工具类代码如下:

package main;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * word
 *
 * @author chx
 * @date 2019/11/13 16:43
 * @return
 */
@Slf4j
public class CustomDocument extends XWPFDocument {
    public CustomDocument(OPCPackage pkg) throws IOException {
        super(pkg);
    }

    public CustomDocument() {
        super();
    }

    /**
     * @param id
     * @param width     宽
     * @param height    高
     * @param paragraph 段落
     */
    public void createPicture(int id, int width, int height, XWPFParagraph paragraph) {
        int EMU = 9525;
        width *= EMU;
        height *= EMU;
        String blipId = getAllPictures().get(id).getPackageRelationship()
                .getId();
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing()
                .addNewInline();
        String picXml = ""
                + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                + "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
                + id
                + "\" name=\"Generated\"/>"
                + "            <pic:cNvPicPr/>"
                + "         </pic:nvPicPr>"
                + "         <pic:blipFill>"
                + "            <a:blip r:embed=\""
                + blipId
                + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
                + "            <a:stretch>"
                + "               <a:fillRect/>"
                + "            </a:stretch>"
                + "         </pic:blipFill>"
                + "         <pic:spPr>"
                + "            <a:xfrm>"
                + "               <a:off x=\"0\" y=\"0\"/>"
                + "               <a:ext cx=\""
                + width
                + "\" cy=\""
                + height
                + "\"/>"
                + "            </a:xfrm>"
                + "            <a:prstGeom prst=\"rect\">"
                + "               <a:avLst/>"
                + "            </a:prstGeom>"
                + "         </pic:spPr>"
                + "      </pic:pic>"
                + "   </a:graphicData>" + "</a:graphic>";

        inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try {
            xmlToken = XmlToken.Factory.parse(picXml);
        } catch (XmlException xe) {
            xe.printStackTrace();
        }
        inline.set(xmlToken);
        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);
        CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("图片名称");
        docPr.setDescr("描述信息");
    }

    /**
     * 根据指定的参数值、模板,生成 word 文档
     *
     * @param param    需要替换的变量
     * @param template 模板
     */
    public XWPFDocument generateWord(Map<String, Object> param, String template, boolean isTable, int index) throws IOException {
        OPCPackage pack = POIXMLDocument.openPackage(template);
        CustomDocument doc = new CustomDocument(pack);
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        return processParagraphs(paragraphList, param, doc, isTable, index);
    }

    /**
     * 处理段落
     *
     * @param paragraphList
     */
    public XWPFDocument processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param,
                                          CustomDocument doc, boolean isTable, int index) {
        if (paragraphList != null && paragraphList.size() > 0) {
            for (XWPFParagraph paragraph : paragraphList) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    String text = run.getText(0);

                    if (text != null) {
                        boolean isSetText = false;
                        for (Map.Entry<String, Object> entry : param.entrySet()) {
                            String key = entry.getKey();

                            if (text.indexOf(key) != -1) {
                                isSetText = true;
                                String value = entry.getValue().toString();

                                if (!key.contains("IMG")) {
                                    text = text.replace(key, value);
                                } else if (key.contains("IMG")) {
                                    byte[] decode = GenerateImage(value);
                                    text = text.replace(key, "");
                                    ByteArrayInputStream byteInputStream = new ByteArrayInputStream(decode);
                                    try {
                                        int ind = doc.addPicture(byteInputStream, CustomDocument.PICTURE_TYPE_PNG);
                                        doc.createPicture(ind, 550, 340, paragraph);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        if (isSetText) {
                            run.setText(text, 0);
                        }
                    }
                }
            }
            if (isTable) {
                //进行表格文字替换
                Iterator<XWPFTable> it = doc.getTablesIterator();
                int flag = 0;

                while (it.hasNext()) {
                    XWPFTable nowTable = it.next();
                    List<XWPFTableRow> rows = nowTable.getRows();
                    List<List<Object>> sypcjcb = null;

                    if (flag == 0 && index == 1) {
                        sypcjcb = (List<List<Object>>) param.get("ZWTABLE");
                    } else if (flag == 0 && index == 2) {
                        sypcjcb = (List<List<Object>>) param.get("SYPCJCB");
                    } else if (flag == 1 && index == 2) {
                        sypcjcb = (List<List<Object>>) param.get("SYPCB");
                    } else if (flag == 2 && index == 2) {
                        sypcjcb = (List<List<Object>>) param.get("JGCGJEB");
                    }

                    if (sypcjcb != null) {
                        //将每行数据替换
                        for (int i = 0; i < rows.size(); i++) {
                            List<XWPFTableCell> tableCells = rows.get(i).getTableCells();

                            for (int j = 0; j < tableCells.size(); j++) {
                                tableCells.get(j).setText(sypcjcb.get(i).get(j).toString());
                            }
                        }
                    }

                    flag++;
                }
            }
        }

        return doc;
    }

    public byte[] GenerateImage(String imgStr) {
        imgStr = imgStr.replaceAll("data:image/png;base64,", "").replaceAll("\\r\\n", "");
        byte[] b = Base64.getDecoder().decode(imgStr);

        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }

        return b;
    }
}

九、读写文件工具类

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;

public class FileUtil {
    /**
     * 按行读取文件
     */
    public static String ReadFileByLine(String filename) {
        File file = new File(filename);
        InputStream is = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        StringBuilder result = new StringBuilder();
        try {
            is = new FileInputStream(file);
            reader = new InputStreamReader(is);
            bufferedReader = new BufferedReader(reader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufferedReader)
                    bufferedReader.close();
                if (null != reader)
                    reader.close();
                if (null != is)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result.toString();
    }

    /**
     * 按字符读取文件
     *
     * @param filename
     */
    public static String ReadFileByChar(String filename) {
        File file = new File(filename);
        InputStream is = null;
        Reader isr = null;
        StringBuilder result = new StringBuilder();
        try {
            is = new FileInputStream(file);
            isr = new InputStreamReader(is);
            int index;

            while (-1 != (index = isr.read())) {
                result.append((char) index);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
                if (null != isr)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result.toString();
    }

    /**
     * 通过OutputStreamWriter写文件
     *
     * @param filename
     */
    public static void Write2FileByOutputStream(String filename, String context) {
        File file = new File(filename);
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos);
            osw.write(context);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 通过BufferedWriter写文件
     *
     * @param filename
     */
    public static void Write2FileByBuffered(String filename, String context) {
        File file = new File(filename);
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);
            bw.write(context);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != osw) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 通过FileWriter写文件
     *
     * @param filename
     */
    public static void Write2FileByFileWriter(String filename, String context) {
        File file = new File(filename);
        FileWriter fw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write(context);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fw) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

十、获取某些下载页面的链接(有些下载页面有问题,无法直接全选下载,此时可以用此demo获取所有链接)

package tmp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UrlGet {
    private static String tou = "onclick=\"window\\.open\\('";
    private static String wei = "\'";
    
    public static void main(String[] args) {
        regexs(readFileByLineBank("C:\\Users\\chx\\Desktop\\urls.txt"));
    }
    
    public static void regexs(String context){
        Pattern pattern = Pattern.compile(tou+"(.*?)"+wei);
        Matcher m = pattern.matcher(context);
        
        while(m.find()){
            System.out.println(m.group(1));
        }
    }
    
    public static String readFileByLineBank(String filename) {
        File file = new File(filename);
        InputStream is = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        StringBuilder sb = new StringBuilder();
        
        try {
            is = new FileInputStream(file);
            reader = new InputStreamReader(is,"UTF-8");
            bufferedReader = new BufferedReader(reader);
            String line;
            
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufferedReader){
                    bufferedReader.close();
                }
                if (null != reader){
                    reader.close();
                }
                if (null != is){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

比如 onclick="window.open('http://xunlei/xxx/1234.mp4')" 即将程序的tou属性设置为(注意转义!!!!)onclick=\"window\\.open\\('

十一、通过经纬度获取直线距离。

    private static double EARTH_RADIUS = 6378.137;

    private double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);

        double s = 2 * Math.asin(Math.sqrt(
                Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s * 1000;
        return s;
    }

    private double rad(double d) {
        return d * Math.PI / 180.0;
    }

十二、FTP交互工具

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil {
    /**
     * 用户名
     */
    private String uName;
    /**
     * 密码
     */
    private String uPass;

    /**
     * 目标IP
     */
    private String goalIP;
    /**
     * 目标端口
     */
    private int goalPort;

    /**
     * ftp相对地址
     */
    private String remotePath;

    /**
     * 初始化参数
     * 
     * @param goalIp
     * @param goalPort
     * @param remotePath
     */
    public void initParam(String goalIp, int goalPort, String remotePath) {
        this.goalIP = goalIp;
        this.goalPort = goalPort;
        this.remotePath = remotePath;
    }

    /**
     * 从FTP下载文件
     * 
     * @param fileName
     * @param savePath
     * @return
     */
    public boolean downloadFile(String fileName, String savePath) {
        if (isNullOrUndefined(savePath, goalIP, String.valueOf(goalPort), remotePath)) {
            new NullPointerException("savePath保存路径不能为空或先调用initParam()");
            return false;
        }
        FTPClient ftp = new FTPClient();
        OutputStream is = null;
        boolean reuslt = false;
        try {
            ftp.connect(goalIP, goalPort);

            if (!isNullOrUndefined(uName, uPass)) {
                ftp.login(uName, uPass);
            }

            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);// 文件类型为二进制文件

            if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                ftp.enterLocalPassiveMode();// 本地模式
                ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
                FTPFile[] fs = ftp.listFiles();

                for (FTPFile ff : fs) {
                    if (ff.getName().equals(fileName)) {
                        File localFile = new File(savePath + fileName);
                        is = new FileOutputStream(localFile);
                        ftp.retrieveFile(ff.getName(), is);
                        reuslt = true;
                        break;
                    }
                }
            }
            ftp.logout();
        } catch (IOException e) {
            return false;
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    return false;
                }
            }
        }

        return reuslt;
    }

    public String getuPass() {
        return uPass;
    }

    public void setuPass(String uPass) {
        this.uPass = uPass;
    }

    public String getuName() {
        return uName;
    }

    public void setuName(String uName) {
        this.uName = uName;
    }

    public String getGoalIP() {
        return goalIP;
    }

    public void setGoalIP(String goalIP) {
        this.goalIP = goalIP;
    }

    public int getGoalPort() {
        return goalPort;
    }

    public void setGoalPort(int goalPort) {
        this.goalPort = goalPort;
    }

    /**
     * 判断是否为空
     * 
     * @param plains
     * @return
     */
    public boolean isNullOrUndefined(String... plains) {
        if (plains == null) {
            return true;
        }

        for (int i = 0; i < plains.length; i++) {
            if (plains[i] == null || "".equals(plains[i]) || plains[i].length() == 0 || "undefined".equals(plains[i])
                    || "null".equals(plains[i])) {
                return true;
            }
        }
        return false;
    }
}

十三、获取整个文件MD5(非文件内容MD5)

/**
     * 获取文件的md5
     * 
     * @param file
     * @return
     * @throws Exception
     */
    public String getMd5ByFile(File file) throws Exception {
        FileInputStream in = new FileInputStream(file);
        MessageDigest md = MessageDigest.getInstance("MD5");
        MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        md.update(byteBuffer);
        byte[] b = md.digest();
        in.close();
        return byteToHexString(b);
    }

    /**
     * 十六进制转字符串
     * 
     * @param tmp
     * @return
     */
    private String byteToHexString(byte[] tmp) {
        String s;
        char str[] = new char[16 * 2];
        int k = 0;
        for (int i = 0; i < 16; i++) {
            byte byte0 = tmp[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        s = new String(str);
        return s;
    }

 

posted @ 2019-08-13 16:12  chxLonely  阅读(361)  评论(0编辑  收藏  举报