总结的JAVA开发常用的工具类
一、获取本机IP和MAC地址
importjava.net.InetAddress;
importjava.net.NetworkInterface;
importjava.net.SocketException;
importjava.net.UnknownHostException;
/**
* 获取本机IP和MAC地址的工具类
*
* @author CHX
*
*/
public classLocalIPAndMAC {
/**
* 获取mac地址的方法
*
* @param ia
* InetAddress对象
* @return mac地址
* @throws SocketException
*/
private static String getLocalMac(InetAddress ia) throwsSocketException {
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);
}
}
returnsb.toString().toUpperCase();
}
public static voidmain(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() throwsUnknownHostException {
return InetAddress.getLocalHost().getHostAddress();}
}
也可以直接使用InetAddress.getLocalHost().getHostAddress()
二、简易版JAVA生成固定四位短连接
前言:利用base64与md5,生成定长四位的短连接(不包括域名)。本程序和网上的大多数都不同,如果有不对的地方希望能够指出。
举例:http://Nolog/asdasdasd/asdasda/aqwertyuiopasdfghjklzxcvbnm5132456789
效果:
代码:
packagecom.kh.pds.util;importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;importjava.util.Base64;importjava.util.regex.Matcher;importjava.util.regex.Pattern;/*** 短网址的实现,不管多长,都生成四位链接
*
*@authorCHX*/
public classShortURL {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 voidmain(String[] args) {
myTestShort(plainUrl,"Nolog");
}/*** 首先从URL中获取固定格式后的内容
*
*@paramlongUrl 原url
*@paramyuMing 域名*/
public static voidmyTestShort(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进制即可
*
*@paramvalue
*@return
*/
public staticString 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= newString(bytesToHexString(md5.digest(stringBase64.getBytes())));
StringBuilder outChars= newStringBuilder();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)]);
}returnoutChars.toString();
}/*** 将字符串转换为base64编码
*
*@paramtext 原文
*@return
*/
public staticString stringBase64(String text) {returnBase64.getEncoder().encodeToString(text.getBytes());
}/*** 将byte转换为16进制的字符串
*
*@paramsrc
*@return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder= newStringBuilder();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);
}returnstringBuilder.toString();
}
}
三、获取指定类的绝对路径
/**
* 获取指定类的绝对路径
*
* @param c
* @return
*/
public static String getNowClassPath(Class>c) {
return c.getResource("").getPath().replaceFirst("/", "");
}
四、通过JAVA反射机制生成指定XML
importjava.io.ByteArrayOutputStream;
importjava.io.StringReader;
importjava.lang.reflect.Field;
importjava.lang.reflect.Method;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.UUID;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
importjavax.xml.parsers.ParserConfigurationException;
importjavax.xml.transform.OutputKeys;
importjavax.xml.transform.Transformer;
importjavax.xml.transform.TransformerException;
importjavax.xml.transform.TransformerFactory;
importjavax.xml.transform.dom.DOMSource;
importjavax.xml.transform.stream.StreamResult;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.w3c.dom.Node;
importorg.w3c.dom.NodeList;
importorg.xml.sax.InputSource;
importorg.xml.sax.SAXException;
public classxmlUtil{
/**
* 根据传入obj创建请求的xml
*
* @param obj
* 待生成的obj
* @param header
* 待生成的头公共域
* @return Document
* @throws Exception
*/
public Document createXmlObjectReq(Object obj, Object header, boolean ifBody) throwsException {
// 创建公共域
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, newClass[] {});
String invoke = (String) method.invoke(header, newObject[] {});
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, newClass[] {});
String invoke = (String) method.invoke(obj, newObject[] {});
Element Pyr_BkCgyCd =root.createElement(fieldName);
Pyr_BkCgyCd.setTextContent(invoke);
request.appendChild(Pyr_BkCgyCd);
}
transaction.appendChild(Transaction_Body);
}
returnroot;
}
public String xmlToString(Document root) throwsException {
// 创建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 = newByteArrayOutputStream();
tf.transform(new DOMSource(root), newStreamResult(bos));
String string =bos.toString();
bos.close();
returnstring;
}
}
五、生成指定位数(8位以上,且为偶数位)的ID
前排提示:该方法未经过正规测试,用于普通场景没问题(八位数-两千万次无重复)。效率一般,总之慎用。
main方法里是多线程测试,如果有输出,则说明有重复值。
真实使用时,去掉main方法及Runnable
packagekh.pms.test;
importjava.security.MessageDigest;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.UUID;
importkh.pms.tools.StringUtil;
/**
* 获取指定位数唯一id=生成uuid->加密md5(32位)->生成对应十六进制字符串->每两位一转换最终位数
*
* @author CHX
*
*/
public class UniqueIDUtil implementsRunnable {
public static Map code = new HashMap();
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) throwsException {
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 = newStringBuilder();
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)]);
}
returnoutChars.toString();
}
/**
* 将byte转换为16进制的字符串
*
* @param src
* @return
*/
private String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = newStringBuilder();
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);
}
returnstringBuilder.toString();
}
public static voidmain(String[] args) {
for (int i = 0; i < 20; i++) {
UniqueIDUtil idUtil = newUniqueIDUtil();
Thread thread = newThread(idUtil);
thread.start();
}
}
@Override
public voidrun() {
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 booleanisNull(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(newDate());
startDT.add(Calendar.DAY_OF_MONTH,-1);
八、有关word操作
/*** 对请求下载word文件作出回应
*
*@authorchx*@paramdocument
*@paramresponse
*@paramfileName
*@return
*/
public static voidexportWord(XWPFDocument document, HttpServletResponse response,
String fileName)throwsException {
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引入版本号如下:
3.7
maven引入依赖如下:
org.apache.poi
poi
${poi.version}
org.apache.poi
poi-ooxml
${poi.version}
org.apache.poi
poi-scratchpad
${poi.version}
使用说明:我们的项目是提前准备好word模板,进行文字和图片替换,这要比直接生成word文档方便的多的多!!!如果前提不一致,只能去百度一下别的方法。
其中,文字和图片信息封装进Map里,图片是用Base64编码后的字符串。key值是有区别性的,比如文字以word开头,图片以img开头,这样才能在替换过程中知道是替换文字还是图片。
Map中的key值就是Word文档中的预留替换字。调用generateWord方法即可获取一个word文档,可以传给前端,也可写入文件,自行操作。
工具类代码如下:
packagemain;importlombok.extern.slf4j.Slf4j;importorg.apache.poi.POIXMLDocument;importorg.apache.poi.openxml4j.opc.OPCPackage;import org.apache.poi.xwpf.usermodel.*;importorg.apache.xmlbeans.XmlException;importorg.apache.xmlbeans.XmlToken;importorg.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;importorg.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;importorg.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;importjava.io.ByteArrayInputStream;importjava.io.IOException;importjava.util.Base64;importjava.util.Iterator;importjava.util.List;importjava.util.Map;/*** word
*
*@authorchx
* @date 2019/11/13 16:43
*@return
*/@Slf4jpublic class CustomDocument extendsXWPFDocument {public CustomDocument(OPCPackage pkg) throwsIOException {super(pkg);
}publicCustomDocument() {super();
}/***@paramid
*@paramwidth 宽
*@paramheight 高
*@paramparagraph 段落*/
public void createPicture(int id, int width, intheight, 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= ""
+ ""
+ " "
+ " "
+ " " + "
+id+ "\" name=\"Generated\"/>"
+ " "
+ "
"+ " "
+ "
+blipId+ "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ "
+width+ "\" cy=\""
+height+ "\"/>"
+ " "
+ " "
+ " "
+ " "
+ " "
+ " "
+ " " + "";
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 文档
*
*@paramparam 需要替换的变量
*@paramtemplate 模板*/
public XWPFDocument generateWord(Map param, String template, boolean isTable, int index) throwsIOException {
OPCPackage pack=POIXMLDocument.openPackage(template);
CustomDocument doc= newCustomDocument(pack);
List paragraphList =doc.getParagraphs();returnprocessParagraphs(paragraphList, param, doc, isTable, index);
}/*** 处理段落
*
*@paramparagraphList*/
public XWPFDocument processParagraphs(List paragraphList, Mapparam,
CustomDocument doc,boolean isTable, intindex) {if (paragraphList != null && paragraphList.size() > 0) {for(XWPFParagraph paragraph : paragraphList) {
List runs =paragraph.getRuns();for(XWPFRun run : runs) {
String text= run.getText(0);if (text != null) {boolean isSetText = false;for (Map.Entryentry : 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= newByteArrayInputStream(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 it =doc.getTablesIterator();int flag = 0;while(it.hasNext()) {
XWPFTable nowTable=it.next();
List rows =nowTable.getRows();
List> sypcjcb = null;if (flag == 0 && index == 1) {
sypcjcb= (List>) param.get("ZWTABLE");
}else if (flag == 0 && index == 2) {
sypcjcb= (List>) param.get("SYPCJCB");
}else if (flag == 1 && index == 2) {
sypcjcb= (List>) param.get("SYPCB");
}else if (flag == 2 && index == 2) {
sypcjcb= (List>) param.get("JGCGJEB");
}if (sypcjcb != null) {//将每行数据替换
for (int i = 0; i < rows.size(); i++) {
List tableCells =rows.get(i).getTableCells();for (int j = 0; j < tableCells.size(); j++) {
tableCells.get(j).setText(sypcjcb.get(i).get(j).toString());
}
}
}
flag++;
}
}
}returndoc;
}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;
}
}returnb;
}
}
九、读写文件工具类
importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.io.Reader;public classFileUtil {/*** 按行读取文件*/
public staticString ReadFileByLine(String filename) {
File file= newFile(filename);
InputStream is= null;
Reader reader= null;
BufferedReader bufferedReader= null;
StringBuilder result= newStringBuilder();try{
is= newFileInputStream(file);
reader= newInputStreamReader(is);
bufferedReader= newBufferedReader(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();
}
}returnresult.toString();
}/*** 按字符读取文件
*
*@paramfilename*/
public staticString ReadFileByChar(String filename) {
File file= newFile(filename);
InputStream is= null;
Reader isr= null;
StringBuilder result= newStringBuilder();try{
is= newFileInputStream(file);
isr= newInputStreamReader(is);intindex;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();
}
}returnresult.toString();
}/*** 通过OutputStreamWriter写文件
*
*@paramfilename*/
public static voidWrite2FileByOutputStream(String filename, String context) {
File file= newFile(filename);
FileOutputStream fos= null;
OutputStreamWriter osw= null;try{if (!file.exists()) {
file.createNewFile();
}
fos= newFileOutputStream(file);
osw= newOutputStreamWriter(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写文件
*
*@paramfilename*/
public static voidWrite2FileByBuffered(String filename, String context) {
File file= newFile(filename);
FileOutputStream fos= null;
OutputStreamWriter osw= null;
BufferedWriter bw= null;try{if (!file.exists()) {
file.createNewFile();
}
fos= newFileOutputStream(file);
osw= newOutputStreamWriter(fos);
bw= newBufferedWriter(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写文件
*
*@paramfilename*/
public static voidWrite2FileByFileWriter(String filename, String context) {
File file= newFile(filename);
FileWriter fw= null;try{if (!file.exists()) {
file.createNewFile();
}
fw= newFileWriter(file);
fw.write(context);
}catch(IOException e) {
e.printStackTrace();
}finally{if (null !=fw) {try{
fw.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
十、获取某些下载页面的链接(有些下载页面有问题,无法直接全选下载,此时可以用此demo获取所有链接)
packagetmp;importjava.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.Reader;importjava.util.regex.Matcher;importjava.util.regex.Pattern;public classUrlGet {private static String tou = "οnclick=\"window\\.open\\('";private static String wei = "\'";public static voidmain(String[] args) {
regexs(readFileByLineBank("C:\\Users\\chx\\Desktop\\urls.txt"));
}public static voidregexs(String context){
Pattern pattern= Pattern.compile(tou+"(.*?)"+wei);
Matcher m=pattern.matcher(context);while(m.find()){
System.out.println(m.group(1));
}
}public staticString readFileByLineBank(String filename) {
File file= newFile(filename);
InputStream is= null;
Reader reader= null;
BufferedReader bufferedReader= null;
StringBuilder sb= newStringBuilder();try{
is= newFileInputStream(file);
reader= new InputStreamReader(is,"UTF-8");
bufferedReader= newBufferedReader(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();
}
}returnsb.toString();
}
}
比如 οnclick="window.open('http://xunlei/xxx/1234.mp4')" 即将程序的tou属性设置为(注意转义!!!!)οnclick=\"window\\.open\\('
十一、通过经纬度获取直线距离。
private static double EARTH_RADIUS = 6378.137;private double getDistance(double lat1, double lng1, double lat2, doublelng2) {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;returns;
}private double rad(doubled) {return d * Math.PI / 180.0;
}
十二、FTP交互工具
importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream;importorg.apache.commons.net.ftp.FTPClient;importorg.apache.commons.net.ftp.FTPFile;importorg.apache.commons.net.ftp.FTPReply;public classFTPUtil {/*** 用户名*/
privateString uName;/*** 密码*/
privateString uPass;/*** 目标IP*/
privateString goalIP;/*** 目标端口*/
private intgoalPort;/*** ftp相对地址*/
privateString remotePath;/*** 初始化参数
*
*@paramgoalIp
*@paramgoalPort
*@paramremotePath*/
public void initParam(String goalIp, intgoalPort, String remotePath) {this.goalIP =goalIp;this.goalPort =goalPort;this.remotePath =remotePath;
}/*** 从FTP下载文件
*
*@paramfileName
*@paramsavePath
*@return
*/
public booleandownloadFile(String fileName, String savePath) {if(isNullOrUndefined(savePath, goalIP, String.valueOf(goalPort), remotePath)) {new NullPointerException("savePath保存路径不能为空或先调用initParam()");return false;
}
FTPClient ftp= newFTPClient();
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= newFileOutputStream(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;
}
}
}returnreuslt;
}publicString getuPass() {returnuPass;
}public voidsetuPass(String uPass) {this.uPass =uPass;
}publicString getuName() {returnuName;
}public voidsetuName(String uName) {this.uName =uName;
}publicString getGoalIP() {returngoalIP;
}public voidsetGoalIP(String goalIP) {this.goalIP =goalIP;
}public intgetGoalPort() {returngoalPort;
}public void setGoalPort(intgoalPort) {this.goalPort =goalPort;
}/*** 判断是否为空
*
*@paramplains
*@return
*/
public booleanisNullOrUndefined(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
*
*@paramfile
*@return*@throwsException*/
public String getMd5ByFile(File file) throwsException {
FileInputStream in= newFileInputStream(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();returnbyteToHexString(b);
}/*** 十六进制转字符串
*
*@paramtmp
*@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= newString(str);returns;
}