`
1250605829
  • 浏览: 60399 次
  • 性别: Icon_minigender_1
  • 来自: 阜阳
社区版块
存档分类
最新评论

开发中用到过的UTIL类

    博客分类:
  • java
阅读更多

1,加密的Util类

 

/* ========================================================================
 * JCommon : a free general purpose class library for the Java(tm) platform
 * ========================================================================
 *
 * (C) Copyright 2000-2004, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * -------------------------------------
 * AbstractElementDefinitionHandler.java
 * -------------------------------------
 * (C)opyright 2003, by Thomas Morgner and Contributors.
 *
 * Original Author:  Kevin Kelley <kelley@ruralnet.net> -
 *                   30718 Rd. 28, La Junta, CO, 81050  USA.                                                         //
 *
 * $Id: Base64.java,v 1.5 2004/01/01 23:59:29 mungady Exp $
 *
 * Changes
 * -------------------------
 * 23.09.2003 : Initial version
 *
 */
package com.zte.aspportal.comm.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

/**
 * Provides encoding of raw bytes to base64-encoded characters, and
 * decoding of base64 characters to raw bytes.
 * date: 06 August 1998
 * modified: 14 February 2000
 * modified: 22 September 2000
 *
 * @author Kevin Kelley (kelley@ruralnet.net)
 * @version 1.3
 */
public class Base64 {

    /**
     * returns an array of base64-encoded characters to represent the
     * passed data array.
     *
     * @param data the array of bytes to encode
     * @return base64-coded character array.
     */
    public static char[] encode(byte[] data) {
        char[] out = new char[((data.length + 2) / 3) * 4];

        //
        // 3 bytes encode to 4 chars.  Output is always an even
        // multiple of 4 characters.
        //
        for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
            boolean quad = false;
            boolean trip = false;

            int val = (0xFF & data[i]);
            val <<= 8;
            if ((i + 1) < data.length) {
                val |= (0xFF & data[i + 1]);
                trip = true;
            }
            val <<= 8;
            if ((i + 2) < data.length) {
                val |= (0xFF & data[i + 2]);
                quad = true;
            }
            out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
            val >>= 6;
            out[index + 1] = alphabet[val & 0x3F];
            val >>= 6;
            out[index + 0] = alphabet[val & 0x3F];
        }
        return out;
    }

    /**
     * Decodes a BASE-64 encoded stream to recover the original
     * data. White space before and after will be trimmed away,
     * but no other manipulation of the input will be performed.
     *
     * As of version 1.2 this method will properly handle input
     * containing junk characters (newlines and the like) rather
     * than throwing an error. It does this by pre-parsing the
     * input and generating from that a count of VALID input
     * characters.
     **/
    public static byte[] decode(char[] data) {
        // as our input could contain non-BASE64 data (newlines,
        // whitespace of any sort, whatever) we must first adjust
        // our count of USABLE data so that...
        // (a) we don't misallocate the output array, and
        // (b) think that we miscalculated our data length
        //     just because of extraneous throw-away junk

        int tempLen = data.length;
        for (int ix = 0; ix < data.length; ix++) {
            if ((data[ix] > 255) || codes[data[ix]] < 0)
                --tempLen; // ignore non-valid chars and padding
        }
        // calculate required length:
        //  -- 3 bytes for every 4 valid base64 chars
        //  -- plus 2 bytes if there are 3 extra base64 chars,
        //     or plus 1 byte if there are 2 extra.

        int len = (tempLen / 4) * 3;
        if ((tempLen % 4) == 3)
            len += 2;
        if ((tempLen % 4) == 2)
            len += 1;

        byte[] out = new byte[len];


        int shift = 0; // # of excess bits stored in accum
        int accum = 0; // excess bits
        int index = 0;

        // we now go through the entire array (NOT using the 'tempLen' value)
        for (int ix = 0; ix < data.length; ix++) {
            int value = (data[ix] > 255) ? -1 : codes[data[ix]];

            if (value >= 0)// skip over non-code
            {
                accum <<= 6; // bits shift up by 6 each time thru
                shift += 6; // loop, with new bits being put in
                accum |= value; // at the bottom.
                if (shift >= 8)// whenever there are 8 or more shifted in,
                {
                    shift -= 8; // write them out (from the top, leaving any
                    out[index++] = // excess at the bottom for next iteration.
                        (byte) ((accum >> shift) & 0xff);
                }
            }
            // we will also have skipped processing a padding null byte ('=') here;
            // these are used ONLY for padding to an even length and do not legally
            // occur as encoded data. for this reason we can ignore the fact that
            // no index++ operation occurs in that special case: the out[] array is
            // initialized to all-zero bytes to start with and that works to our
            // advantage in this combination.
        }

        // if there is STILL something wrong we just have to throw up now!
        if (index != out.length) {
            throw new Error("Miscalculated data length (wrote " +
                index + " instead of " + out.length + ")");
        }

        return out;
    }


    //
    // code characters for values 0..63
    //
    private static char[] alphabet =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();

    //
    // lookup table for converting base64 characters to value in range 0..63
    //
    private static byte[] codes = new byte[256];

    static {
        for (int i = 0; i < 256; i++)
            codes[i] = -1;
        for (int i = 'A'; i <= 'Z'; i++)
            codes[i] = (byte) (i - 'A');
        for (int i = 'a'; i <= 'z'; i++)
            codes[i] = (byte) (26 + i - 'a');
        for (int i = '0'; i <= '9'; i++)
            codes[i] = (byte) (52 + i - '0');
        codes['+'] = 62;
        codes['/'] = 63;
    }




    ///////////////////////////////////////////////////
    // remainder (main method and helper functions) is
    // for testing purposes only, feel free to clip it.
    ///////////////////////////////////////////////////

    public static void main(String[] args) {
        boolean decode = false;

        if (args.length == 0) {
            System.out.println("usage:  java Base64 [-d[ecode]] filename");
            System.exit(0);
        }
        for (int i = 0; i < args.length; i++) {
            if ("-decode".equalsIgnoreCase(args[i]))
                decode = true;
            else if ("-d".equalsIgnoreCase(args[i]))
                decode = true;
        }

        String filename = args[args.length - 1];
        File file = new File(filename);
        if (!file.exists()) {
            System.out.println("Error:  file '" + filename + "' doesn't exist!");
            System.exit(0);
        }

        if (decode) {
            char[] encoded = readChars(file);
            byte[] decoded = decode(encoded);
            writeBytes(file, decoded);
        }
        else {
            byte[] decoded = readBytes(file);
            char[] encoded = encode(decoded);
            writeChars(file, encoded);
        }
    }

    private static byte[] readBytes(File file) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            InputStream fis = new FileInputStream(file);
            InputStream is = new BufferedInputStream(fis);
            int count = 0;
            byte[] buf = new byte[16384];
            while ((count = is.read(buf)) != -1) {
                if (count > 0)
                    baos.write(buf, 0, count);
            }
            is.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return baos.toByteArray();
    }

    private static char[] readChars(File file) {
        CharArrayWriter caw = new CharArrayWriter();
        try {
            Reader fr = new FileReader(file);
            Reader in = new BufferedReader(fr);
            int count = 0;
            char[] buf = new char[16384];
            while ((count = in.read(buf)) != -1) {
                if (count > 0)
                    caw.write(buf, 0, count);
            }
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return caw.toCharArray();
    }

    private static void writeBytes(File file, byte[] data) {
        try {
            OutputStream fos = new FileOutputStream(file);
            OutputStream os = new BufferedOutputStream(fos);
            os.write(data);
            os.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeChars(File file, char[] data) {
        try {
            Writer fos = new FileWriter(file);
            Writer os = new BufferedWriter(fos);
            os.write(data);
            os.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    ///////////////////////////////////////////////////
    // end of test code.
    ///////////////////////////////////////////////////

}

 

 

 

2,解析xml里面的util类

 

package com.zte.aspportal.comm.util;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.jaxen.JaxenException;
import org.jaxen.dom.DOMXPath;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * 解析XML文件
 * @author zw
 *
 */
public class Config {
	// private static String ETC_PATH = System.getProperty("TOMCAT_HOME");
	private Document document;
	private URL confURL;
	private Logger log = Logger.getLogger(this.getClass());
	public Config(String filename) {
		if (filename.trim().length() == 0) {
			filename = "config.xml";
		}
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			confURL = Config.class.getClassLoader().getResource(filename);
			if (confURL == null) {
				confURL = ClassLoader.getSystemResource(filename);
			}
			if (confURL != null) {
				log.info(confURL.toString());
			} else {
				log.info(filename + " not found: ");
			}
			document = db.parse(confURL.openStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getNodeValue(String xpath) {
		try {
			DOMXPath path = new DOMXPath(xpath);
			if (path == null) {
				log.info("Unresolvable xpath " + xpath);
				return null;
			}
			Node node = (Node) path.selectSingleNode(document
					.getDocumentElement());
			if (node == null) {
				log.info("Xpath " + xpath + " seems void");
				return null;
			}
			if (node.hasChildNodes()) {
				Node child = node.getFirstChild();
				if (child != null)
					return child.getNodeValue();
			} else
				return "";

		} catch (JaxenException e) {
			e.printStackTrace();
		}
		return null;
	}

	public long getLongValue(String xpath, long fallback) {
		try {
			String value = getNodeValue(xpath);
			if (value != null)
				return Long.parseLong(value);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		log.info("Using fallback value ( " + fallback + " ) for "
				+ xpath);
		return fallback;
	}

	public String getStringValue(String xpath, String fallback) {
		String value = getNodeValue(xpath);
		if (value != null)
			return value;
		log.info("Using fallback value ( " + fallback + " ) for "
				+ xpath);
		return fallback;
	}
	
	public int getIntValue(String xpath, int fallback) {
		String value = getNodeValue(xpath);
		if (value != null && !"".equals(value.trim()))
		{
			return Integer.valueOf(value);
		}
		log.info("Using fallback value ( " + fallback + " ) for "
				+ xpath);
		return fallback;
	}

}

 

 

 

3,ftp上传下载的util类

package com.zte.aspportal.comm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;



public class FtpUtil {
	/**
	 * ftp上传方法
	 * @param username  
	 * @param username  
	 * @param password
	 * @param path
	 * @param url
	 * @param filename
	 * @param file
	 * @return
	 */
	public static boolean ftpUploadFile(String url,String username, String password, String path,
			 String filename, File file) {
			boolean success = false;
			//判断上传路径是否存在,如果不存在,则新建一个
			FTPClient ftp = new FTPClient();
			try{
				int reply;
				ftp.connect(url);
				ftp.login(username, password);
				reply = ftp.getReplyCode();
				if(!FTPReply.isPositiveCompletion(reply)){
					ftp.disconnect();
					return success;
				}
				// 转到指定上传目录
				ftp.changeWorkingDirectory(path);
				ftp.setFileType(FTP.BINARY_FILE_TYPE); //设置为2进制上传
				// 将上传文件存储到指定目录
				InputStream input=new FileInputStream(file);
				ftp.storeFile(new String(filename.getBytes(),Constants.UPLOADENCODING), input);
				input.close();
				ftp.logout();
				success = true;
			}catch(IOException e){
				e.printStackTrace();
			}finally{
				if(ftp.isConnected()){
					try{
						ftp.disconnect();
					}catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return success;
	 }
	
	
	/**
	 * Description: 从FTP服务器下载文件
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param remotePath
	 *            FTP服务器上的相对路径
	 * @param fileName
	 *            下载时的默认文件名
	 * @return
	 * @throws IOException 
	 */
	public static boolean ftpDownFile(String url, String username, String password,
			String remotePath, String fileName, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 初始表示下载失败
			boolean success = false;
		
			// 创建FTPClient对象
			FTPClient ftp = new FTPClient();
			try {
				int reply;
				// 连接FTP服务器
				// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
				ftp.connect(url);
				// 登录ftp
				ftp.login(username, password);
				reply = ftp.getReplyCode();
				if (!FTPReply.isPositiveCompletion(reply)) {
					ftp.disconnect();
					return success;
				}
				String realName = remotePath
						.substring(remotePath.lastIndexOf("/") + 1);
				// 转到指定下载目录
				ftp.changeWorkingDirectory(remotePath.substring(0, remotePath
						.lastIndexOf("/") + 1));
				ftp.setFileType(FTP.BINARY_FILE_TYPE);

				String agent = request.getHeader("USER-AGENT");
				if (null != agent && -1 != agent.indexOf("MSIE")) {
					String codedfilename = URLEncoder.encode(fileName, "UTF8");
					response.setContentType("application/x-download");
					response.setHeader("Content-Disposition",
							"attachment;filename=" + codedfilename);
				} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
					String codedfilename = MimeUtility.encodeText(fileName, "UTF8",
							"B");
					response.setContentType("application/x-download");
					response.setHeader("Content-Disposition",
							"attachment;filename=" + codedfilename);
				} else {
					response.setContentType("application/x-download");
					response.setHeader("Content-Disposition",
							"attachment;filename=" + fileName);
				}

				// 设置文件下载头部
				// response.setContentType("application/x-msdownload");// 设置编码
				// response.setContentType("application/octet-stream; CHARSET=UTF-8");
				// response.setHeader("Content-Disposition", "attachement;filename="
				// + new String(fileName.getBytes("ISO8859-1"), "UTF-8"));
				FTPFile[] fs = ftp.listFiles();
				// 遍历所有文件,找到指定的文件
				for (FTPFile ff : fs) {
					String ftpFile = new String(
							ff.getName().getBytes("ISO-8859-1"), "gbk");
					if (ftpFile.equals(realName)) {
						OutputStream out = response.getOutputStream();
						InputStream bis = ftp.retrieveFileStream(ff.getName());

						// 根据绝对路径初始化文件
						// 输出流
						int len = 0;
						byte[] buf = new byte[1024];
						while ((len = bis.read(buf)) > 0) {
							out.write(buf, 0, len);
							out.flush();
						}
						out.close();
						bis.close();
						break;
					}
				}
				ftp.logout();
				// 下载成功
				success = true;
			} catch (IOException e) {
				success = false;
				throw e;
			} finally {
				if (ftp.isConnected()) {
					try {
						ftp.disconnect();
					} catch (IOException ioe) {
					}
				}
			}
			return success;
	}
}

 

 

 

4,sftp协议的上传下载

 

package com.zte.aspportal.comm.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
public class SftpUtil {
	Logger logger = Logger.getLogger(SftpUtil.class);
	public static final String OLD_NAME= "oldname";
	public static final String NEW_NAME= "newname";
	/**
	* 连接sftp服务器
	* @param host 主机
	* @param port 端口
	* @param username 用户名
	* @param password 密码
	* @return
	*/
	public ChannelSftp connect(String host, int port, String username,
		String password) {
		ChannelSftp sftp = null;
		try {
			JSch jsch = new JSch();
			jsch.getSession(username, host, port);
			Session sshSession = jsch.getSession(username, host, port);
			System.out.println("Session created.");
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			System.out.println("Session connected.");
			System.out.println("Opening Channel.");
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			System.out.println("Connected to " + host + ".");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sftp;
	}

	/**
	* 上传文件
	* @param directory 上传的目录
	* @param uploadFile 要上传的文件
	* @param sftp
	*/
	public boolean upload(String url,String username,String password,String port,String directory,String filename, File file) {
		boolean success = false;
		try {
			
			ChannelSftp sftp=this.connect(url, Integer.valueOf(port), username, password);
			sftp.cd(directory);
			InputStream input=new FileInputStream(file);
			sftp.put(input, new String(filename.getBytes(),Constants.UPLOADENCODING));
			//关闭连接
			sftp.disconnect();
			success = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return success;
	}

	/**
	* 下载文件
	* @param directory 下载目录
	* @param downloadFile 下载的文件
	* @param saveFile 存在本地的路径
	* @param sftp
	*/
	public String download(String url,String username,String password,String port,String directory, String downloadFile,String saveFile,HttpServletRequest request,HttpServletResponse response) {
		String success = null;

		ChannelSftp sftp=connect(url, Integer.valueOf(port), username, password);
		try {
			sftp.cd(directory);
			String agent = request.getHeader("USER-AGENT");
			if (null != agent && -1 != agent.indexOf("MSIE")) {
				String codedfilename = downloadFile;
				response.setContentType("application/x-download");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + codedfilename);
			} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
				String codedfilename = MimeUtility.encodeText(downloadFile.replaceAll(" ", "_"), "UTF8",
						"B");
				response.setContentType("application/x-download");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + codedfilename);
			} else {
				response.setContentType("application/x-download");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + downloadFile);
			}
			
			OutputStream out = response.getOutputStream();
			InputStream bis = sftp.get(downloadFile);

			// 根据绝对路径初始化文件
			// 输出流
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = bis.read(buf)) > 0) {
				out.write(buf, 0, len);
				out.flush();
			}
			out.close();
			bis.close();
			//关闭连接
			sftp.disconnect();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SftpException e) {
			//success = e.getCause().getMessage();
			//logger.info(success);
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return success;
	}
	
	/**
	 * 
	 * @param url
	 * @param username
	 * @param password
	 * @param directory
	 * @param fileList 格式 修改文件名称列表,其中的每个map中,原先名字键值为SftpUtil.OLD_NAME 需要修改后的名字键值为SftpUtil.NEW_NAME
	 * @return
	 */
	public boolean reName(String url,String username,String password,String port,String directory,List<Map<String, String>> fileList) {
		boolean success = false;
		try {
			ChannelSftp sftp=connect(url, Integer.valueOf(port), username, password);
			sftp.cd(directory);
			for(int i=0;i<fileList.size();i++){
				Map<String, String> map = fileList.get(i);
				sftp.rename(map.get(OLD_NAME), map.get(NEW_NAME));
			}
			//关闭连接
			sftp.disconnect();
			success=true;
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return success;
	}
	
	/**
	 * 返回文件名称中包含fileNameContains所给字符串的文件列表
	 * @param url
	 * @param username
	 * @param password
	 * @param directory
	 * @param fileNameContains
	 * @return
	 */
	public List<String> getFileList(String url,String username,String password,String port,String directory,String fileNameContains){
		List<String> fileList = new ArrayList<String>();
		try {
			ChannelSftp sftp=connect(url, Integer.valueOf(port), username, password);
			sftp.cd(directory);
			Vector vector = sftp.ls(directory);
			if(fileNameContains==null){
				fileNameContains = "";
			}
			for(int i=0;i<vector.size();i++){
				LsEntry lsEntry = (LsEntry)vector.get(i);
				String fileName = lsEntry.getFilename();
				if (fileName.contains(fileNameContains)) {
					fileList.add(fileName);
				}
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return fileList;
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		ChannelSftp sftp=new SftpUtil().connect("10.10.10.10",22, "user", "password");
		try {
			String string="/home/user/test2/LY/";
//			String string="1000000100_L S¨¦verin 48  M Pr¨¦sla";
			String string2="/home/user/test2/1000000100_L Sverin 48  M Prsla/";
			sftp.cd(new String(string.getBytes("UTF-8"),"ISO-8859-1"));
			sftp.cd(new String(string.getBytes("UTF-8"),"UTF-8"));
			sftp.cd(new String(string.getBytes("UTF-8"),"GBK"));
			sftp.cd(new String(string.getBytes("ISO-8859-1"),"ISO-8859-1"));
			sftp.cd(new String(string.getBytes("ISO-8859-1"),"UTF-8"));
			sftp.cd(new String(string.getBytes("ISO-8859-1"),"GBK"));
			sftp.cd(new String(string.getBytes("GBK"),"ISO-8859-1"));
			sftp.cd(new String(string.getBytes("GBK"),"UTF-8"));
			sftp.cd(new String(string.getBytes("GBK"),"GBK"));
			System.out.println(new String(new String(new String(string.getBytes("UTF-8"), "ISO-8859-1")
                    .getBytes("ISO-8859-1"), "UTF-8").getBytes(), "ISO-8859-1"));
			sftp.cd(string);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

 

 

5,生成校验码的util类

 

package com.zte.aspportal.comm.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RandImgCreater extends  HttpServlet {
	
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

@Override
  protected void service(HttpServletRequest request, HttpServletResponse response){
	
     HttpSession  session=request.getSession(true);
		
	 //设置页面不缓存   
     response.setHeader("Pragma","No-cache");   
     response.setHeader("Cache-Control","no-cache");   
     response.setDateHeader("Expires", 0);   
 
    // 在内存中创建图象   
     int width=53, height=18;   
     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);   
 
   // 获取图形上下文   
     Graphics g = image.getGraphics();   
 
   //生成随机类   
     Random random = new Random();   
 
   // 设定背景色   
     g.setColor(this.getRandColor(200,250));   
     g.fillRect(0, 0, width, height);   
 
   //设定字体   
     g.setFont(new Font("Times New Roman",Font.BOLD,16));     
 
  //画边框   
     //g.setColor(new Color());   
     //g.drawRect(0,0,width-1,height-1);   
 
 
 // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到   
    g.setColor(this.getRandColor(160,200));   
    for (int i=0;i<155;i++){   
       int x = random.nextInt(width);   
       int y = random.nextInt(height);   
       int xl = random.nextInt(12);   
       int yl = random.nextInt(12);   
       g.drawLine(x,y,x+xl,y+yl);   
    }   
 
 // 取随机产生的认证码(4位数字)   
     String sRand="";   
     for (int i=0;i<4;i++){   
         String rand=String.valueOf(random.nextInt(10));   
         sRand+=rand;  
         
 // 将认证码显示到图象中   
      g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成   
      g.drawString(rand,13*i+3,16);
 }   
 
 // 将认证码存入SESSION   
    session.setAttribute("rand",sRand);   
 
 
 // 图象生效   
    g.dispose();   
 
 // 输出图象到页面   
    try{
       ImageIO.write(image, "JPEG", response.getOutputStream());   
     }catch(Exception e){
    	e.printStackTrace();
    }
   }
   
  private  Color getRandColor(int fc,int bc){//给定范围获得随机颜色   
        Random random = new Random();   
        if(fc>255) fc=255;   
        if(bc>255) bc=255;   
        int r=fc+random.nextInt(bc-fc);   
        int g=fc+random.nextInt(bc-fc);   
        int b=fc+random.nextInt(bc-fc);   
        return new Color(r,g,b);   
 }   
}

 

 

 

package com.zte.aspportal.comm.util;

import java.util.Date;
import java.util.Random;

public class RandUtil {

	public static String gettempName(String filename) {
		String postfix = "";
		postfix = filename.substring(filename.lastIndexOf("."));
		Date nowTime = new Date();
		String name = nowTime.getTime() + postfix;
		return name;
	}
	
   public static String getRandomString(int length,int type) {   
        String figureBase = "0123456789";
        String letterBase = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String letterAndFigureBase = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();   
        StringBuffer sb = new StringBuffer();
        switch (type) {
            case 0:
                 for (int i = 0; i < length; i++) {   
                        int number = random.nextInt(figureBase.length());   
                        sb.append(figureBase.charAt(number));   
                 }   
                break;
            case 1:
                 for (int i = 0; i < length; i++) {   
                        int number = random.nextInt(letterBase.length());   
                        sb.append(letterBase.charAt(number));   
                 }   
                break;
            case 2:
                 for (int i = 0; i < length; i++) {   
                        int number = random.nextInt(letterAndFigureBase.length());   
                        sb.append(letterAndFigureBase.charAt(number));   
                 }   
                break;
            default:
                 for (int i = 0; i < length; i++) {   
                        int number = random.nextInt(figureBase.length());   
                        sb.append(figureBase.charAt(number));   
                 }   
                break;
        }
        return sb.toString();   
    } 
}

 

 

6,简单的邮件发送stmp3协议的util类

package com.zte.aspportal.comm.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



/**
 *  简单邮件(不带附件的邮件)发送器
 *  @author zhangwei
 *
 */
public class SimpleMailSender {
   /**   
   * 以文本格式发送邮件   
   * @param mailInfo 待发送的邮件的信息   
   */    
   public boolean sendTextMail(MailSenderInfo mailInfo)  
   		throws  MessagingException { 
	   
	    // 判断是否需要身份认证    
	    MyAuthenticator authenticator = null;    
	    Properties pro = mailInfo.getProperties();   
	    if (mailInfo.isValidate()) {    
	     // 如果需要身份认证,则创建一个密码验证器    
	        authenticator = new MyAuthenticator(mailInfo.getEmail(), mailInfo.getPassword());    
	    }   
	     // 根据邮件会话属性和密码验证器构造一个发送邮件的session    
	    Session sendMailSession = Session.getDefaultInstance(pro,authenticator);    
		     // 根据session创建一个邮件消息    
		    Message mailMessage = new MimeMessage(sendMailSession);    
		    // 创建邮件发送者地址    
		    Address from = new InternetAddress(mailInfo.getFromAddress());    
		    // 设置邮件消息的发送者    
		    mailMessage.setFrom(from);    
		    // 创建邮件的接收者地址,并设置到邮件消息中    
		    Address to = new InternetAddress(mailInfo.getToAddress());    
		    mailMessage.setRecipient(Message.RecipientType.TO,to);    
		    // 设置邮件消息的主题    
		    mailMessage.setSubject(mailInfo.getSubject());    
		    // 设置邮件消息发送的时间    
		    mailMessage.setSentDate(new Date());    
		    // 设置邮件消息的主要内容    
		    String mailContent = mailInfo.getContent();    
		    mailMessage.setText(mailContent);    
		    // 发送邮件    
		    Transport.send(mailMessage);   
		    return true;    
	  }  
   /**   
    * 以html形式发送邮件   
    * @param mailInfo 待发送的邮件的信息   
    */  
   public static boolean sendHtmlMail(MailSenderInfo   mailInfo) {
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			authenticator = new MyAuthenticator(mailInfo.getEmail(), mailInfo.getPassword());   
		}
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		sendMailSession.setDebug(true);
		try {
			Message mailMessage = new MimeMessage(sendMailSession);
			Address from = new InternetAddress(mailInfo.getFromAddress());
			mailMessage.setFrom(from);
			Address to = new InternetAddress(mailInfo.getToAddress());
			mailMessage.setRecipient(Message.RecipientType.TO,to);
			mailMessage.setSubject(mailInfo.getSubject());
			mailMessage.setSentDate(new Date());
			//MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
			Multipart mainPart = new MimeMultipart();
			//创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			//设置HTML内容
			html.setContent(mailInfo.getContent(),"text/html; charset=utf-8");
			mainPart.addBodyPart(html);
			// 将MiniMultipart对象设置为邮件内容
			mailMessage.setContent(mainPart);
			//发送邮件
			mailMessage.saveChanges();
		  	Transport transport = sendMailSession.getTransport("smtp");
			transport.connect(mailInfo.getMailServerHost(),mailInfo.getUserName(),mailInfo.getPassword());
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
			transport.close();
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}
}


 

 

 

7,常用的日期转换等工具util类

package com.zte.aspportal.comm.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.zte.aspportal.user.bean.Developer;




/**
 * 工具类
 * @author zw
 *
 */
public class SysUtils
{
    public static Logger log = Logger.getLogger(SysUtils.class);



    /**
     * 获得当前日期和时间
     *
     * @return String 当前日期和时间,格式:yyyy-MM-dd HH:mi:ss
     */
    public static String getCurDateTime()
    {
        SimpleDateFormat nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return nowDate.format(new Date());
    }

    /**
     * 格式化日期, yyyyMMddHHmmss -> yyyy-MM-dd HH:mm:ss
     * @param str
     * @return
     */
    public static String formatDateFullTime(String str){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    	Date date = null;
    	try {
			date = sdf.parse(str);
		} catch (Exception e) {
			log.error(e);
		}
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	return sdf.format(date);
    }

    /**
     * 格式化日期,将日期从yyyy-MM-dd HH:mm:ss转换为yyyyMMddHHmmss
     *
     * @param strDateTime
     *            String
     * @return String
     */
    public static String formatDateTime(String strDate)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try
        {
            date = sdf.parse(strDate);
        } catch (ParseException e)
        {
            log.error("SysUtils formatDateTime is exception ", e);
        }
        sdf = new SimpleDateFormat("yyyyMMddHHmmss");

        return sdf.format(date);
    }


    /**
     * 比较两个日期yyyyMMddHHmmss类型大小
     * firstDate>secondDate return 1
     * firstDate=secondDate return 0
     * firstDate<secondDate return -1
     * @param firstDate
     * @param secondDate
     * @return
     */
    public static int compareDate(String firstDate,String secondDate)
    {
    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
         Date date = null;
         Date date2 = null;
         try
         {
             date = sdf.parse(firstDate);
             date2 = sdf.parse(secondDate);
             return date.compareTo(date2);
         } catch (ParseException e)
         {
             log.error("SysUtils formatDateTime is exception ", e);
         }
         return -1;
    }

	/**
	 * 格式化日期,将日期转换为yyyyMMddHHmmss
	 *
	 * @param date
	 * @return
	 */
	public static String formatLongDateTime(Date date) {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(date);
	}

	/**
	 * 格式化日期字符串
	 * 2011-10-10 转换为20111010
	 * @param str
	 * @return
	 */
	public static String formatStrTime(String str) {
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	        Date date = null;
	        try
	        {
	            date = sdf.parse(str);
	        } catch (ParseException e)
	        {
	            log.error("SysUtils formatDateTime is exception ", e);
	        }
	        sdf = new SimpleDateFormat("yyyyMMdd");

	        return sdf.format(date);
	}


    /**
     * 判断String是否为空
     *
     * @param str
     * @return
     */
    public static boolean isNull(String str)
    {
        boolean flag = false;
        if (str == null || "".equals(str))
        {
            flag = true;
        }
        return flag;
    }

    /**
     * 获得当前日期
     *
     * @return String 当前日期,格式:yyyyMMddHHmmss
     */
    public static String getCurDate()
    {
        SimpleDateFormat nowDate = new SimpleDateFormat("yyyyMMddHHmmss");
        return nowDate.format(new Date());
    }
   /**
    * 获取需要的日期格式
    * @param currentDate    当前日期格式
    * @param formateDate    转换日期格式
    * @param date			传入值
    * @return
    */
    public static String getFormateDate(String currentDate,String formateDate,String date)
    {
    	try {
			Date dt = new SimpleDateFormat(currentDate).parse(date);
			return new SimpleDateFormat(formateDate).format(dt);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
    }
    
    
    /**
     * 获取指定年限后的日期 格式:yyyyMMddHHmmss
     * @return
     */
    public static String getCurYearDate(Integer year){
    	String date = getCurDate();
    	Integer yyyy = Integer.parseInt(date.substring(0,4))+year;
    	String result = yyyy+date.substring(4);
    	return result;
	}

    /**
     * 非空判断
     *
     * @param param
     *            参数
     * @return string
     */
    public static String trim(String param)
    {
        return null == param ? "" : param.trim();
    }

    /**
     * 设置当前登录用户信息至session
     * @param request
     * @param developer
     */
    public static void setCurrUSERINFO(HttpServletRequest request, Developer developer)
    {
       request.getSession().setAttribute("userinfo",developer);
    }

    /**
     * 移除当前登录信息
     * @param request
     */
    public static void removeCurrUSERINFO(HttpServletRequest request)
    {
       request.getSession().removeAttribute("userinfo");
    }

    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    public static Developer getCurrUSERINFO(HttpServletRequest request)
    {
        Developer developer = (Developer)request.getSession().getAttribute("userinfo");

        return developer;
    }
}

 

 

 

8,ftp ,sftp上传下载的开关控制类

 

package com.zte.aspportal.comm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.jcraft.jsch.ChannelSftp;
import com.zte.toolstore.tools.InitConstants;

public class UploadUtil {

	/**
	 * 判断开关中是什么文件上传方式
	 * @return
	 */
	public static boolean getUploadType(){
		String uploadtype = InitConstants.getInstance().getString("uploadtype");
		if (uploadtype==null||uploadtype.equals("")) {
			uploadtype="0";
		}
		return Integer.valueOf(uploadtype) == 0 ? false:true;
	}
	
	/**
	 * 上传方法
	 * @param url
	 * @param username
	 * @param password
	 * @param path
	 * @param filename
	 * @param file
	 * @return
	 */
	public static boolean uploadFile(String url,String username, String password, String port,String path,
			 String filename, File file) {
		boolean success = false;
		checkDirAndCreate(path);
		//sftp方式上传
		if(getUploadType()){
				SftpUtil sftpUtil = new SftpUtil();
				success=sftpUtil.upload(url,username,password,port,path,filename,file);
				return success;
		}
		//ftp方式上传
		else{
			FtpUtil ftpUtil = new FtpUtil();
			success= ftpUtil.ftpUploadFile(url, username, password, path, filename, file);
			return success;
		}
	 }
	
	/**
	 * Description: 从FTP服务器下载文件
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param remotePath
	 *            FTP服务器上的相对路径
	 * @param fileName
	 *            下载时的默认文件名

	 * @return
	 * @throws IOException 
	 */
	public static boolean downFile(String url, String username, String password,String port,
			String remotePath, String fileName, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 初始表示下载失败
		boolean success = false;
		String success2 = null;
		if(getUploadType()){//sftp方式下载
			SftpUtil sftpUtil = new SftpUtil();
			remotePath = remotePath.substring(0,remotePath.lastIndexOf("/")+ 1);
			success2=sftpUtil.download(url,username,password,port,remotePath,fileName,fileName,request,response);
			if(success2==null){
				success = true;
			}
			return success;
		}else {//ftp方式下载
			FtpUtil ftpUtil = new FtpUtil();
			success=ftpUtil.ftpDownFile(url, username, password, remotePath, fileName, request, response);
			return success;
		}
		
	}
	

	
	/**
	 * 检查一个路径是否存在,如果不存在,则创建该目录
	 *
	 * @param fileDir
	 *              目录路径
	 * @return 如果目录存在,则返回True,否则返回False。
	 */
	public static boolean checkDirAndCreate(String fileDir) {
		File file = new File(fileDir);
		if (!file.exists()) {
			return file.mkdirs();
		}
		return true;
	}
}

 

 

 

 

9,解析word的util类

 

package com.zte.aspportal.comm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.struts2.ServletActionContext;

import com.zte.aspportal.capability.bean.CapaBilityMethod;
import com.zte.aspportal.capability.dao.impl.CapaBilityMethodDaoImpl;
import com.zte.toolstore.tools.InitConstants;

public class WordParser {
/**
 * 读取word2003文本
 */
	  public String extractMSWordText(File file) {
	    	try {
	    		InputStream input = new FileInputStream(file);
				HWPFDocument msWord=new HWPFDocument(input);
				Range range = msWord.getRange();
				String msWordText = range.text();
				return msWordText;
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
	    }
/**
 * 读取word2003图片
 */
	  public void extractImagesIntoDirectory(String directory,File file) throws IOException {
	    	InputStream input = new FileInputStream(file);
	    	HWPFDocument msWord=new HWPFDocument(input);
	        PicturesTable pTable = msWord.getPicturesTable();
	        int numCharacterRuns = msWord.getRange().numCharacterRuns();
	        for (int i = 0; i < numCharacterRuns; i++) {

	            CharacterRun characterRun = msWord.getRange().getCharacterRun(i);

	            if (pTable.hasPicture(characterRun)) {

	                System.out.println("have picture!");

	                Picture pic = pTable.extractPicture(characterRun, false);

	                String fileName = pic.suggestFullFileName();

	                OutputStream out = new FileOutputStream(new File(directory
	                        + File.separator + fileName));

	                pic.writeImageContent(out);
	            }
	        }
	    }
/**
* 读取word2007文本
*/
		public String extractContent(File document)
		{
			String contents="";
			String wordDocxPath=document.toString();
			try {
				OPCPackage opcPackage=POIXMLDocument.openPackage(wordDocxPath);
				XWPFDocument xwpfd=new XWPFDocument(opcPackage);
				POIXMLTextExtractor ex = new XWPFWordExtractor(xwpfd);
				//读取文字
				contents= ex.getText().trim();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return contents;
		}
/**
* 读取word2007图片
*/
		public String[] extractImage(File document,String imgPath){//document获取word路径,imgPath图片保存路径
			String wordDocxPath = document.toString();
			String[] photopath = null;
			try {
				//载入文档
				OPCPackage opcPackage= POIXMLDocument.openPackage(wordDocxPath);
				XWPFDocument xwpfd = new XWPFDocument(opcPackage);
				//建立图片文件目录
				File file = new File(imgPath);
				if(!file.exists()){
					file.mkdir();
				}
				//获取所有图片
				List<XWPFPictureData> piclist=xwpfd.getAllPictures();
				photopath = new String[piclist.size()];
				for (int i = 0; i < piclist.size(); i++) {
					XWPFPictureData pic = (XWPFPictureData)piclist.get(i);
					Integer index = Integer.parseInt(pic.getFileName().substring(5,pic.getFileName().lastIndexOf(".")));//确定图片顺序
					//获取图片数据流
					byte[] picbyte = pic.getData();
					//将图片写入本地文件
					String path ="/uploadfiles/cap"+File.separator+UUIDGenerate.getUUID()+".jpg";
					FileOutputStream fos = new FileOutputStream(imgPath+path);
					fos.write(picbyte);
					photopath[index-1]=path;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return photopath;
		}
		/**
		 * 测试
		 */
		public static void main(String[] args) {
	    		WordParser word = new WordParser();
	    		File file = new File("d://word/sample1.docx");
	    		String[] photoPath = word.extractImage(file,"D:\\workSpace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\aspportal");
	    		String wordText=word.extractContent(file);
	    		System.out.println(wordText);
	    		wordText = wordText.replaceAll("\n", "<br/>");
	    		wordText = wordText.replaceAll("\t", "&nbsp;");
	    		String[] wordArray = wordText.split("--------");
	    		Integer methodSize = wordArray.length/6;
	    		for(int i=0;i<methodSize;i++)
	    		{
	    			CapaBilityMethod method = new CapaBilityMethod();
		    		method.setSrvtypeid("2");
		    		method.setMethodname(wordArray[6*i+1].replaceAll("<br/>", ""));
		    		method.setWebdesc(wordArray[6*i+2].replaceFirst("<br/>", ""));
		    		method.setParams(wordArray[6*i+3].replaceFirst("<br/>", ""));
		    		method.setAuth(wordArray[6*i+4].replaceFirst("<br/>", ""));
		    		method.setSample(photoPath[i]);
		    		method.setErrors(wordArray[6*i+6].replaceFirst("<br/>", ""));
		    		CapaBilityMethodDaoImpl methodDao = new CapaBilityMethodDaoImpl();
		    		methodDao.addMethod(method);
	    		}
		}
}

 

分享到:
评论

相关推荐

    开发中用到的常用到的类

    这是很有用的开发常用的类,包括一些util、 config的类

    apr-util-1.3.9-win32-src.zip_APR-util_apr 1.3._apr-uti_apr.1.3.9

    apr-1 util,开发第三方库,在secondlife中用到

    StringUtil.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    HttpClientUtil.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    Base64Util.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    MD5Util.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    java常用工具类的使用

    在Java程序设计过程中,对应日期和时间的格式化,还有一个简单的格式化方式,就是java.text.SimpleDateFormat,该类中用字符串指定日期和时间的格式,字符串中的字符称为模式字符,模式字符区分大小写。常见的模式...

    最新Hibernate jar 架包(9个)

    commons-collections-3.2.jar Apache Commons包中的一个, 包含了一些Apache开发的集合类,功能比java.util.*强大。必须使用的jar包 javassist-3.12.0.GA.jar 这个包也是必须的 jta.jar 当使用JTA规范时,必须加入,...

    双鱼林安卓Android代码生成器 v2.0.zip

    双鱼林基于安卓Android代码生成器是一款生成安卓手机程序的代码生成器 基于分层模式设计思想,生成的代码直接导入Eclipse软件就可以用的! ...res/drawable-mdpi:程序界面中用到的图片资源文件!

    Util:公共组件,Examples chinass.github.ioUtil

    造成各个项目中用到的组件都不一样,有些项目可能同时使用多个前端组件,这样就带来项目维护困难,开发人员需要不同项目学习了解不同前端组件等问题,由此,该公共组件应运而生。该组件基于jquery、boostrap以及...

    BaseHttpSSLSocketFactory.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    DemoBase.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    SDKConstants.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    LogUtil.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    SDKConfig.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    SecureUtil.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

Global site tag (gtag.js) - Google Analytics