`
3213213333332132
  • 浏览: 78825 次
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
java类加载顺序 java基础
package com.demo;

/**
 * @Description 类加载顺序
 * @author FuJianyong
 * 2015-2-6上午11:21:37
 */
public class ClassLoaderSequence {
	
	String s1 = "成员属性"; 
	
	static String s2 = "静态属性";
	
	String s3;
	
	static String s4;
	
	static {
		System.out.println("静态代码快");
	}
	
	{
		System.out.println("代码快");
	}
	
	public static void test1() {
		System.out.println("静态方法");
	}
	
	public void test2() {
		System.out.println("普通方法");
	}
	
	public static void main(String[] args) {
//		ClassLoaderSequence.test1();
		new ClassLoaderSequence().test2();
	}
}
java杨辉三角 java基础
package com.algorithm;

/**
 * @Description 杨辉三角
 * @author FuJianyong
 * 2015-1-22上午10:10:59
 */
public class YangHui {
	public static void main(String[] args) {
		//初始化二维数组长度
		int[][] yanghui = new int[10][];

		/*
		 * 动态初始化二维数组
		 * 第一步	杨辉三角初始化		
			0	
			0	0	
			0	0	0	
			0	0	0	0	
			0	0	0	0	0	
			0	0	0	0	0	0	
			0	0	0	0	0	0	0	
			0	0	0	0	0	0	0	0	
			0	0	0	0	0	0	0	0	0
		 */
		for(int i=0;i<yanghui.length;i++) {
			   yanghui[i] = new int[i];  
		}		
		/*
		 * 第二步	杨辉三角第一位和最后以为数值都是1		
						 
			1	
			1	1	
			1	0	1	
			1	0	0	1	
			1	0	0	0	1	
			1	0	0	0	0	1	
			1	0	0	0	0	0	1	
			1	0	0	0	0	0	0	1	
			1	0	0	0	0	0	0	0	1
		 */
		for(int i=0;i<yanghui.length;i++) {
			for(int j=0;j<i;j++) {
				if(i==0 || j==0 || j==yanghui[i].length-1)
				yanghui[i][j] = 1;
			}
		}
		/*
		 * 第三步	杨辉三角第n行n列的数值等于n-1行n-1列(左上方)加上n-1行n列(正上方)的数值											
						
			1	
			1	1	
			1	2	1	
			1	3	3	1	
			1	4	6	4	1	
			1	5	10	10	5	1	
			1	6	15	20	15	6	1	
			1	7	21	35	35	21	7	1	
			1	8	28	56	70	56	28	8	1
		 */
		for(int i=0;i<yanghui.length;i++) {
			for(int j=0;j<i;j++) {
				//处理剩下没赋值的数组
				if(i!=0 && j!=0 && j!=yanghui[i].length-1) {
					yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
				}
			}
		}
		/*
		 * 输出杨辉三角	
		 * 第二步可以和第三步合并
		 */
		for(int i=0;i<yanghui.length;i++) {
			for(int j=0;j<i;j++) {
				System.out.print(yanghui[i][j] +"\t");  
			}
			System.out.println();
		}
	}
}
基本数据类型和引用类型的初始值 java基础
package com.array;

/**
 * @Description 测试初始值
 * @author FuJianyong
 * 2015-1-22上午10:31:53
 */
public class ArrayTest {
    
	ArrayTest at;
	String str;
	byte bt;
	short s;
	int i;
	long l;
	float f;
	double d;
	char c;
	boolean b;
	/**
	 * 基本数据类型和引用类型初始值
	 */
	public void testInitialize() {
		System.out.println(str+" "+bt+" "+s+" "+i+" "+l+" "+f+" "+d+" "+c+" "+b+" ");	
	}
	
	ArrayTest[] atA = new ArrayTest[1];
	String[] strA = new String[1];
	byte[] btA = new byte[1];
	short[] sA = new short[1];;
	int[] iA = new int[1];;
	long[] lA = new long[1];;
	float[] fA = new float[1];;
	double[] dA = new double[1];;
	char[] cA = new char[1];;
	boolean[] bA = new boolean[1];;
	/**
	 * 基本数据类型和引用类型数组初始值
	 */
	public void testInitializeArray() {
		System.out.println(strA[0]+" "+btA[0]+" "+sA[0]+" "+iA[0]+" "+lA[0]+" "+fA[0]
		                   +" "+dA[0]+" "+cA[0]+" "+bA[0]+" ");
	}
    /** 
     * test
     * @param args
     * output
     * null 0 0 0 0 0.0 0.0  false
     */
    public static void main(String[] args) {
    	ArrayTest at = new ArrayTest();
    	at.testInitialize();
    	at.testInitializeArray();
    }
}
java冒泡排序 java基础
package com.algorithm;

/**
 * @Description 冒泡
 * @author FuJianyong
 * 2015-1-22上午09:58:39
 */
public class MaoPao {
	public static void main(String[] args) {
		int[] mao = {17,50,26,18,9,100,88};//静态分配数组初始数值
		int temp = 0; 
		//外部循环执行遍历冒泡
		for(int i=0;i<mao.length;i++) {
			//内部循环执行相邻两个数组比较,大的就冒泡
			for(int j=0;j<mao.length-1;j++) {
				//如果左边的数组大于右边的数组
				if(mao[j]>mao[j+1]) {
					temp = mao[j+1];//右边的数组赋值给临时对象
					mao[j+1] = mao[j];//左边的数组赋值给右边的数组
					mao[j] = temp;//临时对象赋值给左边的数组
				}
			}
		}
		for(int i=0;i<mao.length;i++) {
			System.out.print(" "+mao[i]);
		}
	}
}
MybatisHelloWorld mybatis
//测试入口TestMyBatis 
package com.base.helloworld.test;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.base.helloworld.bean.User;
import com.base.helloworld.mapper.Mapper;

public class TestMyBatis {
      public static SqlSessionFactory getSessionFactory() {
    	  String config = "com/base/helloworld/config.xml";
    	  SqlSessionFactory sessionFactory = null;
    	  try {
			sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(config));
		  } catch (IOException e) {
			e.printStackTrace();
		  }
		  return sessionFactory;
      } 
      public static void main(String[] args) {
    	  	SqlSession sqlSession = getSessionFactory().openSession();
    	  	Mapper mapper = sqlSession.getMapper(Mapper.class);
    	  	User user = mapper.selectById(2);
    	  	System.out.println(user.getName()+"  "+user.getPassword());
      }
}
//配置文件config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
  <typeAliases>
       <typeAlias type="com.base.helloworld.bean.User" alias="User"/>
  </typeAliases>
  <environments default="development">
  		<environment id="development">
  			<transactionManager type="jdbc" />
  			<dataSource type="POOLED" >
  			   	<property name="driver" value="com.mysql.jdbc.Driver"/>
  			   	<property name="url" value="jdbc:mysql://192.168.1.10:3306/XXX?useUnicode=true&characterEncoding=utf-8"/>
  			   	<property name="username" value="XXXXXX" />
  			   	<property name="password" value="XXXXXX" />
  			</dataSource>
  		</environment>
  </environments>
  <mappers>
     <mapper resource="com/base/helloworld/mapper/mapper.xml"/>
  </mappers>
</configuration>
//模型User
package com.base.helloworld.bean;

public class User {
	
   private String name;
   
   private String password;

	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
   
}
// 接口Mapper
package com.base.helloworld.mapper;

import com.base.helloworld.bean.User;

public interface Mapper {
	
	User selectById(int id);	
	
}
//操作数据库mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.base.helloworld.mapper.Mapper">
   <select id="selectById" parameterType="int" resultType="User">
   	SELECT * FROM t_user where ID = #{id}
   </select>
</mapper>

ImageIO读取一张图片改变大小 javaio流
package com.demo;

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

import javax.imageio.ImageIO;

/**
 * @Description 读取一张图片改变大小
 * @author FuJianyong
 * 2015-1-20上午10:48:49
 */
public class ImageIORead {
	/**
	 * 改变图片的大小
	 * @return boolean
	 */
	public static boolean readImage() {
	//设定要生成的新图片的宽高和图片格式	
	BufferedImage newbi = new BufferedImage(500, 500, BufferedImage.TYPE_INT_BGR);
	    boolean val = false;
		try {
			//从硬盘读取一张图片
			BufferedImage oldbi = ImageIO.read(new File("E:/DEMO/dd.jpg"));
			//把读过的来的图片画到设定好的新图片上
			newbi.getGraphics().drawImage(oldbi, 0, 0, 500, 500, null);
			//通过ImageIO写到硬盘上去
		    val = ImageIO.write(newbi, "png", new File("E:/DEMO/ddd.png"));
			return val;
		}catch(IOException e) {
			e.printStackTrace();
		}
		return val;
    }
    public static void main(String[] args) {
    	System.out.println(readImage());
    }
}
ImageIO写图片到硬盘 javaio流
package awt;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 用ImageIO写一个图片到硬盘上
 * @author Fujianyong
 * 2015-1-17 下午08:57:27
 */
public class ImageIODemo {
	
	/**
	 * 创建一个BufferedImage图片缓冲区对象并指定它宽高和类型
	 * 这样相当于创建一个画板,然后可以在上面画画
	 */
	BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_BGR);
	
	/**
	 * 要生成图片的类型,可以是JPG GIF JPEG PNG等...
	 */
	final String picType = "png";
     
	/**
	 * 成生成图片的保存路径和图片名称
	 */
	final File file = new File("D:/myeclipseTestData/test." + picType);  
	
	/**
	 * 通过指定参数写一个图片
	 * @param bi 
	 * @param picType
	 * @param file
	 * @return boolean 如果失败返回一个布尔值
	 */
	public static boolean writeImage(BufferedImage bi, String picType, File file) {
	    //拿到画笔
		Graphics g = bi.getGraphics();
		//画一个图形系统默认是白色
		g.fillRect(0, 50, 200, 100);
		//设置画笔颜色
		g.setColor(new Color(12,123,88));
		//设置画笔画出的字体风格
		g.setFont(new Font("隶书", Font.ITALIC, 30));
		//写一个字符串
		g.drawString("我是IO流图片", 10, 100);		
		//释放画笔
		g.dispose();
		//将画好的图片通过流形式写到硬盘上
		boolean val = false;
		try {
			val = ImageIO.write(bi, picType, file);		
		} catch (IOException e) {			
			e.printStackTrace();
		}
		return val;
	}
	public static void main(String[] args) {
		ImageIODemo image = new ImageIODemo();
		System.out.println(writeImage(image.bi, image.picType, image.file));
	}
}
md5 java加密
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MDFive {
    public static void main(String[] args) {
    	String md5Str = "cqmy0_YSDS2";    	
    	System.out.println(md5(md5Str));
    }
    public static String md5(String md5Str) {
    	StringBuffer sb = new StringBuffer();
    	try {
    		//获得消息摘要md5
			MessageDigest md5 = MessageDigest.getInstance("md5");
			//以md5的方式加密    java.security.MessageDigest的设计体现了工厂模式
			byte[] tempMd5 = md5.digest(md5Str.getBytes());
			int temp = 0;
			for(byte s: tempMd5) {
				temp = s;
				if(temp<0) temp+=256; //负变正
				if(temp<16) sb.append("0"); //小于16前面加0,这能保证生成的密文长度为32
				//把数字加工成为十六进制字符串——装到字符串缓冲区
				sb.append(Integer.toHexString(temp));
			}			
		} catch (NoSuchAlgorithmException e) {		   
			e.printStackTrace();
		}
    	return sb.toString().toUpperCase();
    }
}
SpringTask定时任务 spring
public class CleanTempFileTask extends TimerTask {

	private final Logger log = Logger.getLogger(this.getClass());

 	//过期时间
	private final int OUT_DATE_DURATION = 1000 * 60 * 60;

	@Override
        //实现TimerTask的抽象方法
	public void run() {
		log.info("开始清理过期临时文件");
		//临时文件的路径
		String tempFileDir = ConfigHolder.getInstance().getFileSavePath() + File.separator + Constant.PATH_TEMPFILE + File.separator;
		File tempDir = new File(tempFileDir);
		removeOutDateFiles(tempDir);
		log.info("清理临时过期文件完毕");
	}

	private void removeOutDateFiles(File dir) {
		File[] fileList = dir.listFiles();
		//将文件夹里的文件逐个判断并悄无声息的删掉
		for (File file : fileList) {			
			if (file.isFile()) {
				// 如果文件的修改时间是OUT_DATE_DURATION毫秒前的则删除
				boolean isOlder = FileUtils.isFileOlder(file, System.currentTimeMillis() - OUT_DATE_DURATION);
				if (isOlder) {
					log.debug("删除过期临时文件==>" + file.getAbsolutePath());
					FileUtils.deleteQuietly(file);
				}
			} else if (file.isDirectory()) {
				removeOutDateFiles(file);
			}
		}
	}
	
}

//bean
	<!-- 定时任务1:清理临时文件 -->
	<!-- 任务 -->
	<bean id="cleanTempFileTask" class="com.*.comm.task.CleanTempFileTask"></bean>
	<task:scheduled-tasks>
		<!--  一个小时清理一次 -->
		<task:scheduled ref="cleanTempFileTask" method="run"  fixed-delay="#{1000*60*60}" />
	</task:scheduled-tasks>
java结合spring发邮件 spring
public void sendMailByAsynchronousMode(final Email email) {
//taskExecutor : org.springframework.core.task.TaskExecutor
		taskExecutor.execute(new Runnable() {
			public void run() {
				try {
					sendMailBySynchronizationMode(email);
				} catch (Exception e) {
					log.info(e);
				}
			}
		});
	}
	public void sendMailBySynchronizationMode(Email email) throws MessagingException, IOException {
		log.debug(email.toString());
// mailSender : org.springframework.mail.javamail.JavaMailSender
		MimeMessage mime = mailSender.createMimeMessage();
//import org.springframework.mail.javamail.MimeMessageHelper;
		MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8");
		helper.setFrom(email.getFromAddress());// 发件人
		helper.setTo(email.getToAddress());// 收件人
		helper.setReplyTo(email.getFromAddress());// 回复到
		helper.setSubject(email.getSubject());// 邮件主题
		helper.setText(email.getContent(), true);// true表示设定html格式
		mailSender.send(mime);
	}

// spring bean 配置

<!-- 邮件服务 -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="protocol" value="${email.protocol}"></property>
		<property name="host" value="${email.host}"></property>
		<property name="port" value="${email.port}"></property>
		<property name="username" value="${email.username}"></property>
		<property name="password" value="${email.password}"></property>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">false</prop>
				<prop key="mail.smtp.timeout">30000</prop>
				<!-- 如果mail服务器是ssl认证,则去掉这里的注释符号 -->
				<prop key="mail.smtp.socketFactory.port">465</prop>
				<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
				<prop key="mail.smtp.socketFactory.fallback">false</prop>
			</props>
		</property>
	</bean>
	
	<bean id="taskExecutor"
		class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<property name="corePoolSize" value="5"></property>
		<property name="maxPoolSize" value="30"></property>
		<property name="keepAliveSeconds" value="0"></property>
	</bean>
sql查城市 sql
-- db_yhm_city
SELECT * FROM db_yhm_city WHERE class_parent_id = 1 -- 海南 class_id = 9 港、奥、台 class_id = 33、34、35

SELECT * FROM db_yhm_city WHERE class_parent_id =169

SELECT d1.class_name, d2.class_name, d3.class_name FROM db_yhm_city d1 
RIGHT JOIN db_yhm_city d2 ON d1.class_id = d2.class_parent_id 
RIGHT JOIN db_yhm_city d3 ON d2.class_id = d3.class_parent_id
WHERE d3.class_id = 1445

-- tb1_publicarea
SELECT * FROM tbl_publicarea WHERE parentid = 0 -- 海南 areaid = 21

SELECT * FROM tbl_publicarea WHERE parentid = 21

SELECT t1.areaname, t2.areaname, t3.areaname FROM tbl_publicarea t1 
RIGHT JOIN tbl_publicarea t2 ON t1.areaid = t2.parentid 
RIGHT JOIN tbl_publicarea t3 ON t2.areaid = t3.parentid 
WHERE t3.areaid = 264

-- t_area
SELECT * FROM t_area WHERE parentid IS NULL -- 海南 id = 460000

SELECT * FROM t_area WHERE parentid = 460000  -- 省直辖 id = 469000

SELECT * FROM t_area WHERE parentid = 469000

SELECT a1.name, a2.name, a3.name FROM t_area a1 
RIGHT JOIN t_area a2 ON a1.id = a2.parentid 
RIGHT JOIN t_area a3 ON a2.id = a3.parentid 
WHERE a3.id = 419001

SELECT * FROM t_area WHERE NAME LIKE "%省直辖%"

SELECT * FROM t_area WHERE id = 419000 -- 省直辖
java年份判断封装类 java基础
package com.test;

/**
 * @Description 年份判断封装类
 * @author Fujianyong
 * 2014-12-30上午11:11:21
 */
public class Year {
	
	/**
	 * 可以通过year变量来获得存取年份值
	 */
	private int year;
		
	/**
	 * @return year
	 */
	public int getYear(){
		return year;
		
	}
	/**
	 * @param year
	 */
	public void setYear(int year){
		this.year=year;
		
	}

	/**
	 * 通过构造方法生成带有年份值的对象
	 * @param year
	 */
	public Year(int year){
		super();
		this.year=year;
	}
	
	/**
	 * 判断当前构造的对象的年份值是否是闰年
	 * @return
	 */
	public boolean isLeap(){
		if((year%4 == 0 && year%100 != 0)||(year%400 == 0))
			return true;
		else 
			return false;	
	}

	/**
	 * 这里重载了isLeap() 通过该方法可以判断任意年份属否是闰年
	 * @param year
	 * @return 
	 */
	public boolean isLeap(int year) {
		if((year%4 == 0 && year%100 != 0)|| (year%400 == 0))
			return true;
		else
			return false;
	}
}	
java获取年、时间差、闰年天数计算 java工具
package com.test;

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

public class TimeCheckOut { 
	public static void main(String[] args) throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
//		java.util.Date now = df.parse("2004-03-26 13:31:40");
//		java.util.Date date=df.parse("2004-01-02 11:30:24");
//		Date testDate = new Date();
//		long testL = testDate.getTime();
//		long l=now.getTime()-date.getTime();
//		Calendar c = Calendar.getInstance();
//		c.add(Calendar.YEAR, 5);
		int nowYear = Calendar.getInstance().get(Calendar.YEAR);
		int year = nowYear - 1970;
		Year y = new Year(2014);
		int temp=0;
		int d = 0;
		for(int i=1970;i<=y.getYear();i++) {
			if(y.isLeap(i))
				temp=366;
			else 
				temp=365;
				
			d += temp;
		}		
		long l=new Date().getTime();
		long day=l/(24*60*60*1000);
		long hour=(l/(60*60*1000)-day*24);
		long min=((l/(60*1000))-day*24*60-hour*60);
		long s=(l/1000-day*24*60*60-hour*60*60-min*60);
		long ms =(l-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
		
		System.out.println(
			"判断闰年后的天数 \n"+ d +"\n"+
			"1970年到现在已经过了"+ year +"年\n" +
			"格林威治时间过了"+day+"天"+hour+"小时"+min+"分"+s+"秒"+ms+"毫秒\n" +
			 "今天是年末\n" + df.format(l)
		);
	}
}
Java获取UUID java工具
import java.util.UUID;

public class UUIDTest {
	public static void main(String[] args) {
		System.out.println(UUID.randomUUID().toString().toUpperCase().replaceAll("-", ""));
	}
}
js异步三级联动下拉框 js
//三级联动
   省/直辖市<select id="province"></select>
   市/省直辖<select id="city"></select>
   县/区 <select id="area"></select>

   <!-- JQuery方式 -->
   <script type="text/javascript">
    $().ready(function() {
        var coco = "coco";
            //ajax
            $.ajax({
				url: "Test",
				dataType: "json",
				data: {myName: "coco"},
				success: function(data) {
					for(var i=0;i<data.length;i++) {
					 alert(data[i].city + data[i].id);
					}				
				}
				
            });
            // getJSON  
	    $.getJSON('Test', function(data) {
			alert(data)
			alert(data[1].city)
			alert(data[0].id)
	    });
    });
   </script>
   
   <!-- JS方式 -->
   <script type="text/javascript">
      window.onload = function() {
		var req;
		if(window.XMLHttpRequest) {
 			req = new XMLHttpRequest();
		}else if(window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}else {alert("您的浏览器版本太旧咯");}
		if(req) {
			req.open("post", "Test", true);
			req.send(null);
			req.onreadystatechange = function() {
				if(req.readyState == 4) {
					if(req.status == 200) {
					var data = eval('('+req.responseText+')');
				    var province = document.getElementById("province");
					for(var i=0;i<data.length;i++) {
						province.options.add(new Option(data[i].city, data[i].id));
					}
			    	var city = document.getElementById("city");
			    	var option = document.createElement("option");
					option.value = 1;
					option.innerHTML = "北京";
					city.appendChild(option);	
					}else {
						alert("现在的状态" + req.statusText);
					}
				}else {
					document.getElementById("province").innerText = "加载中...";
				}
			}
		}
      }
   </script>
js年份下拉框 js
 //年份 
   <select id="year"></select>
   <script type="text/javascript">
     window.onload = function() {       
        var year = document.getElementById("year");
        var divValue = document.getElementById("divValue");

	    var date = new Date();
	    for(var i=1992;i<=date.getFullYear();i++) {
	       year.options.add(new Option(i, i));	       	
	    }
	    year.onchange = function() {
		    alert(divValue.innerHTML)//以后用到innerHTML 注意火狐不兼容innerText
		    alert(year.value)
	    }
     }
   </script>
Global site tag (gtag.js) - Google Analytics