`
收藏列表
标题 标签 来源
文件copy io
  public static void copy(String fromUrl, String toUrl) throws Exception {
        FileInputStream fin = new FileInputStream(fromUrl);
        FileOutputStream fout = new FileOutputStream(toUrl);
        FileChannel fcin = fin.getChannel();
        FileChannel fcout = fout.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
         buffer.clear();
            int r = fcin.read(buffer);
            if (r == -1) {
                break;
            }
            buffer.flip();
            fcout.write(buffer);
        }
    }

 public static void main(String[] args) throws Exception {
        // String infile =
        // "E:\\workspace\\las\\src\\com\\energysh\\las2\\aop\\mail\\SendAlertMail.java";
        // String outfile =
        // "E:\\bk\\las\\src\\com\\energysh\\las2\\aop\\mail\\SendAlertMail.java.txt";
        String infile = "E:\\workspace\\las\\src\\com\\energysh\\strategy\\po\\";
        String outfile = "E:\\bk\\las\\src\\com\\energysh\\strategy\\po\\";
        File f = new File("E:\\workspace\\las\\src\\com\\energysh\\strategy\\po\\");
        if (f.isDirectory()) {
            File[] temps = f.listFiles();
            for (File temp : temps) {
                String nameTemp = temp.getName();
                if(nameTemp.endsWith("java")){
                String   fromUrl=infile+nameTemp;
                String   toUrl=outfile+nameTemp+".txt";
                copy(fromUrl,toUrl);
                System.out.println(temp.getName());
                }
            }
        }
}
去掉注释 记两条去除注释的正则表达式
/\*.*\*/
PropertiesManage
package Properties;

import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;



public class PropertiesManage {
	private final static String fileName="root.properties";
	public static Properties props = new Properties();
	private static ConcurrentHashMap<Object,Object> map;
	static {

		try {
			InputStream in = PropertiesManage.class.getClassLoader()
					.getResourceAsStream(fileName);
			props.load(in);
			setMap();
		} catch (Exception e) {
			System.out.println("properties populate error.");
			e.printStackTrace();
		}
	}
	private static void  setMap(){
		map = new ConcurrentHashMap<Object,Object>();
		map.putAll(props);
	}
	public static Object getValue(Object key){
		if(map.containsKey(key)){
			return map.get(key);
		}
		return "";
	}
	
	public static void main(String[] args) {
		System.out.println(PropertiesManage.getValue("aaa"));
	}
}
Excel
package Excel;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import Date.Simple;





public class Excel {

	/**
	 * 检查ExcelSheet
	 * 
	 * @param input
	 * @return
	 * @throws InvalidFormatException
	 * @throws IOException
	 */
	public static boolean checkFactorWorkbook(InputStream input) throws InvalidFormatException, IOException {
		// 根据输入流创建Workbook对象
		Workbook wb = WorkbookFactory.create(input);
		// 读取Sheet0工作簿
		int sheetCount=wb.getNumberOfSheets();
		if(sheetCount<0){
			return false;
			}
		for(int i=0;i<sheetCount ;i++){
			Sheet sheet0 = wb.getSheetAt(i);
			for (Row row : sheet0) {
				for (Cell cell : row) {
					String result = getCellValue(cell);
					return !StringUtils.isEmpty(result);
				}
			}
		}

		return false;
	}

	


	/**
	 * 获得单元格的值
	 * 
	 * @param cell
	 * @return
	 */
	public static String getCellValue(Cell cell) {
		String result = null;

		switch (cell.getCellType()) {
		// 读取布尔值
		case Cell.CELL_TYPE_BOOLEAN:
			result = Boolean.toString(cell.getBooleanCellValue());
			break;
		// 读取日期或者数字
		case Cell.CELL_TYPE_NUMERIC:
			if (DateUtil.isCellDateFormatted(cell)) {
				result = Simple.format(cell.getDateCellValue());
			} else {
				result = String.valueOf(cell.getNumericCellValue());
			}
			break;
		// 读取公式
		case Cell.CELL_TYPE_FORMULA:
			result = cell.getCellFormula();
			break;
		// 读取字符串
		case Cell.CELL_TYPE_STRING:
			result = cell.getRichStringCellValue().toString();
			break;
		}

		return result;
	}

}
img
package IMG;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;

public class Image {

	/**
	 * @Title getImgeHexString
	 * @Description 图片转换成二进制字符串
	 * @param path
	 *           图片地址
	 * @param type
	 *            图片类型
	 * @return String 转换结果
	 * @throws
	 */
	public static String getImgeHexString(String path, String type) {
		String res = null;
		try {
            File file = new File(path);
            FileImageInputStream fis = new FileImageInputStream(file);

			BufferedImage bm = ImageIO.read(fis);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ImageIO.write(bm, type, bos);
			bos.flush();
			byte[] data = bos.toByteArray();

			res = byte2hex(data);
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	/**
	 * @title 根据二进制字符串生成图片
	 * @param data
	 *            生成图片的二进制字符串
	 * @param fileName
	 *            图片名称(完整路径)
	 * @param type
	 *            图片类型
	 * @return
	 */
	public static void saveImage(String data, String fileName, String type) {

		BufferedImage image = new BufferedImage(300, 300,
				BufferedImage.TYPE_BYTE_BINARY);
		ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, type, byteOutputStream);
			// byte[] date = byteOutputStream.toByteArray();
			byte[] bytes = hex2byte(data);
			System.out.println("path:" + fileName);
			RandomAccessFile file = new RandomAccessFile(fileName, "rw");
			file.write(bytes);
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 反格式化byte
	 * 
	 * @param s
	 * @return
	 */
	public static byte[] hex2byte(String s) {
		byte[] src = s.toLowerCase().getBytes();
		byte[] ret = new byte[src.length / 2];
		for (int i = 0; i < src.length; i += 2) {
			byte hi = src[i];
			byte low = src[i + 1];
			hi = (byte) ((hi >= 'a' && hi <= 'f') ? 0x0a + (hi - 'a')
					: hi - '0');
			low = (byte) ((low >= 'a' && low <= 'f') ? 0x0a + (low - 'a')
					: low - '0');
			ret[i / 2] = (byte) (hi << 4 | low);
		}
		return ret;
	}

	/**
	 * 格式化byte
	 * 
	 * @param b
	 * @return
	 */
	public static String byte2hex(byte[] b) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] out = new char[b.length * 2];
		for (int i = 0; i < b.length; i++) {
			byte c = b[i];
			out[i * 2] = Digit[(c >>> 4) & 0X0F];
			out[i * 2 + 1] = Digit[c & 0X0F];
		}

		return new String(out);
	}

}
后台验证 letter,number,mobile,phone,zip,email,url
public class Cheak{
      public boolean isAllLetter(String inString) {
		Pattern p = Pattern.compile("[a-zA-Z]+");
		Matcher m = p.matcher(inString);
		return m.matches();
	}

	public boolean isNumber(String number) {
		return org.apache.commons.lang.math.NumberUtils.isNumber(number);
	}

	public boolean isMobile(String mobile) {
		Pattern p = Pattern.compile("[+]?[0-9]{11,15}");
		Matcher m = p.matcher(mobile);
		return m.matches();
	}

	public boolean isPhone(String phone) {
		Pattern p = Pattern.compile("[0][1-9]{2,3}[-]?[0-9]{6,9}");
		Matcher m = p.matcher(phone);
		return m.matches();
	}

	public boolean isZip(String zip) {
		Pattern p = Pattern.compile("[0-9]{5,8}");
		Matcher m = p.matcher(zip);
		return m.matches();
	}

	public boolean isEmail(String email) {
		Pattern p = Pattern.compile("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher m = p.matcher(email);
		return m.matches();
	}

	public boolean isMemberName(String name) {
		Pattern p = Pattern.compile("[a-zA-Z0-9_]{3,15}");
		Matcher m = p.matcher(name);
		return m.matches();
	}

	public boolean isPs(String name) {
		Pattern p = Pattern.compile("[a-zA-Z0-9]{6,20}");
		Matcher m = p.matcher(name);
		return m.matches();
	}
	
	public boolean isURL(String url) {
		Pattern p = Pattern.compile("(http[s]?|ftp):\\/\\/[^\\/\\.]+?\\..+\\w");
		Matcher m = p.matcher(url);
		return m.matches();
	}
}
时间处理util
public class  DateUtil{
        public Date getDate(String date) {
		String[] dates = StringUtils.split(date, "-");
		GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
		gc.set(new Integer(dates[0]).intValue(),
				new Integer(dates[1]).intValue() - 1,
				new Integer(dates[2]).intValue());
		return gc.getTime();
	}

	public Date getAllDatePart(String date) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.parse(date);
	}

	public String getDateyyyMMdd(String date) {
		return formateDate(getDate(date), "yyyy-MM-dd");
	}
	
	public String getDateyyyMMdd(Date date) {
		return formateDate(date, "yyyy-MM-dd");
	}

	public Date TimestampToDate(java.sql.Timestamp tt) {
		GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
		gc.setTimeInMillis(tt.getTime());
		return gc.getTime();
	}
	public String TimestampToString(java.sql.Timestamp tt,String formate) {
	    SimpleDateFormat df = new SimpleDateFormat(formate);
        return df.format(tt);
    }
	public String formateDate(Date date, String pattern) {
		return org.apache.commons.lang.time.DateFormatUtils.format(date,pattern);
	}
/**
	 * 把时间转为标准形�?	 * 
	 * @param dt
	 * @return 转换后的形式
	 */
	public static String toString(Date dt, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String str = sdf.format(dt);
		return str;
	}

	public static Date toDate(String dt) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = null;
		try {
			d = df.parse(dt);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}
/**  
	   * 得到几天前的时间  
	   * @param d  
	   * @param day  
	   * @return  
	   */  
	  public Date getDateBefore(Date d,int day){   
	   Calendar now =Calendar.getInstance();   
	   now.setTime(d);   
	   now.set(Calendar.DATE,now.get(Calendar.DATE)-day);   
	   return now.getTime();   
	  }   
	     
	  /**  
	   * 得到几天后的时间  
	   * @param d  
	   * @param day  
	 
	   * @return  
	   */  
	  public Date getDateAfter(Date d,int day){   
	   Calendar now =Calendar.getInstance();   
	   now.setTime(d);   
	   now.set(Calendar.DATE,now.get(Calendar.DATE)+day);   
	   return now.getTime();   
	  }  

	  /**
	   * 功能:得到日期的星期
	   * 1:星期一  ...7:星期�?
	   * @date 2011-6-13 下午04:01:13
	   * @param d
	   * @return
	   */
	  public Integer getDayOfWeek(Date d){
		  Calendar now = Calendar.getInstance();
		  now.setTime(d);
		  int myWeek = now.get(Calendar.DAY_OF_WEEK)-1;//�?為生活常用的星期
		  if(myWeek==0)//如果�?星期天改�?
			  myWeek=7;
		  return myWeek;
	  }
	  
	  /**
	   * 功能:返回月份中的某�?��
	   * @date 2011-6-13 下午04:15:21
	   * @param d
	   * @return
	   */
	  public Integer getDayOfMonth(Date d){
		  Calendar now = Calendar.getInstance();
		  now.setTime(d);
		  return now.get(Calendar.DAY_OF_MONTH);
	  }
}	  
FTP访问操作 java
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.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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


public class FtpUtil {

	private String hostname, username, password;
	int port=21;
	FTPClient ftp=null;

	public FtpUtil(String hostname,String username,String password,int port){
		this.hostname=hostname;
		this.username=username;
		this.password=password;
		this.port=port;
		ftp=new FTPClient();
		login();
	}
	public FtpUtil(String hostname,String username,String password){
		this.hostname=hostname;
		this.username=username;
		this.password=password;
		ftp=new FTPClient();
		login();
	}
    private void login(){
    	try {
			ftp.connect(this.hostname,this.port);
			if(!ftp.login(username, password)){
				ftp.logout();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    public FTPClient getFTPClient(){
    	return ftp;
    }
    /**
     * 改变远程工作
     * @param pathname
     * @return
     */
    public boolean changeRemotDir(String pathname){
    	try {
    		return ftp.changeWorkingDirectory(pathname);
    		
		} catch (Exception e) {
			return false;
		}
    }
    
    public FTPFile[] getRomoteFiles() throws IOException{
    	return this.ftp.listFiles();
    }
    
    public boolean  delRomoteFile(FTPFile file) throws IOException{
    	 return this.ftp.deleteFile(file.getName());
    }
    
    public void delRomoteFiles(List<FTPFile> files) throws IOException{
   	 for(FTPFile file:files){
   		this.ftp.deleteFile(file.getName());
   	 }
   }
    
    /**
     * 关闭连接
     */
    public void close(){
    	try {
			ftp.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    
    /**
     * 
     * @param remoteFileName 远程文件名称,空则为本地文件名
     * @param localFilePath 本地被上传的文件名
     * @return uploadError 上传失败 ok上传成功
     * @throws FileNotFoundException 
     */
    public String uploadFile(String remoteFileName,String localFilePath){
		try {
			File file = new File(localFilePath);
			MyUtil cUtil = MyUtil.getInstance();
			Date date = new Date();
			String da=cUtil.formateDate(date, "yyyyMMddHHmmss");
			//String flast="."+da+".mavkftpfile";
			InputStream input = new FileInputStream(file);
			if(null==remoteFileName||"".equals(remoteFileName)){
				remoteFileName=file.getName();//+flast;
			}
			ftp.storeFile(remoteFileName, input);
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "uploadError";
		}
    	return "ok";
    }
    
    
    /**
     * 
     * @param remoteFileName 远程文件名称,空则为本地文件名
     * @param localFilePath 本地被上传的文件名
     * @return uploadError 上传失败 ok上传成功
     * @throws IOException 
     * @throws FileNotFoundException 
     */
    public String uploadBossFile(String remoteFileName,String localFilePath) throws IOException{
    	    this.ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			File file = new File(localFilePath);
			InputStream input = new FileInputStream(file);
			if(null==remoteFileName||"".equals(remoteFileName)){
				remoteFileName=file.getName();
			}
			ftp.storeFile(remoteFileName, input);
			input.close();
			return "ok";
    }
    /**
     * 
     * @return
     */
    public String downloadFile(String remoteFileName,String localFilePath){
        try {
            FileOutputStream fos = new FileOutputStream(localFilePath); 
            ftp.setBufferSize(1024); 
            //设置文件类型(二进制) 
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
            ftp.retrieveFile(remoteFileName, fos); 
            fos.close();
        } catch (Exception e) { 
            e.printStackTrace(); 
            return "downloadError";
        }
        return "ok";
    }
    /**
     * 下载当前目录下的所有文件
     * @return
     */
    public List<String> downloadAllFile(){
    	List<String> inList = new ArrayList<String>();
    	MyUtil mu = MyUtil.getInstance();
    	try {
             //设置文件类型(二进制) 
             ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
             FTPFile[] ffs =ftp.listFiles();
             for(FTPFile ff:ffs){
            	 //System.out.println(ff.getTimestamp().getTime());
            	 FileOutputStream fos = new FileOutputStream(mu.getRealPath()+"/downloadFile/"+ff.getName()); 
            	 ftp.retrieveFile(ff.getName(), fos); 
            	 fos.close();
            	 inList.add(mu.getRealPath()+"/downloadFile/"+ff.getName());
             }
		} catch (Exception e) {
		     	
		}
    	return inList;
    }
    
    public static void main(String[] args) throws IOException {
    	FtpUtil fu = new FtpUtil("192.168.1.200","zhangsan","1234",21);
    	List<String> inList=fu.downloadAllFile();
    	String line;
	    for(String in:inList){
	    	java.io.BufferedReader read = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(in)));
	    	while(null!=(line=read.readLine())){
	    		System.out.println(line);
	    	}
	    	read.close();
	    }
    }
    
    
    
    
    
}
Global site tag (gtag.js) - Google Analytics