Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | About

1.4. 類型

1.4.1. String

1.4.1.1. 隨機字元串

			
	public String randomString(String chars, int length) {
		Random rand = new Random();
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < length; i++) {
			buf.append(chars.charAt(rand.nextInt(chars.length())));
		}
		return buf.toString();
	}
	
	/**
     * 獲取4位隨機驗證碼
     * @return
     */
    public static String getValidationCode(){
        return String.valueOf((new Random().nextInt(8999) + 1000));
    }

    /**
     * 獲取6位隨機驗證碼
     * @return
     */
    public static String getValidationCode(){
        return String.valueOf((new Random().nextInt(899999) + 100000));
    }	
			
			

1.4.1.2. 字元串替換處理

			
public class Test {

	public Test() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("2010-09-11T20:00:30".replace("T", " "));
	}
}
			
			
			
				{"status":0,"message":"","bankcode":"ABOC;IBC;CCTB;ICBC"}
				轉換後
				{\"status\":0,\"message\":\"\",\"bankcode\":\"ABOC;IBC;CCTB;ICBC\"}
			
			
package test;

public class str {

	public static void main(String[] args) {
		String jsonString = "{\"status\":0,\"message\":\"\",\"bankcode\":\"ABOC;IBC;CCTB;ICBC\"}";
		System.out.println(jsonString);
		System.out.println(jsonString.replace("\"", "\\\""));
	}

}
			
			
1.4.1.2.1. 正則表達式查找與替換

查找特定字元並替換為找到的內容

				
package cn.netkiller.type;

public class ragexTest {

	public ragexTest() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String str = "<html>Netkiller</html>";
		String regex = "<html>|</html>";
		//運行結果返回 Netkiller
		System.out.println(str.replaceAll(regex, ""));
		
		// 運行結果返回 Neo
		System.out.println("CN/NETKILLER/WWW/Neo_Chen".replaceAll(".*/(.+)_Chen", "$1"));
	}
}
				
				

1.4.1.3. substring

			
例如:
String str = "helloword!!!";

System.out.println(str.substring(1,4));

System.out.println(str.substring(3,5));

System.out.println(str.substring(0,4));

將得到結果為:

ell

lo 

hell
			
			

1.4.1.4. string to timestamp

Timestamp轉化為String:

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //定義格式,不顯示毫秒
				Timestamp now = new Timestamp(System.currentTimeMillis());
				//獲取系統當前時間
				String str = df.format(now);
			

String轉化為Timestamp:

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String time = df.format(new Date());
				Timestamp ts = Timestamp.valueOf(time);
			

1.4.2. 類型轉換

1.4.2.1. Long to String

			
	public class MainClass {

	  public static void main(String[] arg) {
	    long b = 12L;
	    System.out.println(String.valueOf(b));   
	
	  }
	}
			
			

1.4.3. Date

java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp 區別

		
package cn.netkiller.java.date;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) {
		System.out.println("Hello World!");

		// Get standard date and time
		java.util.Date utilDate = new java.util.Date();
		long javaTime = utilDate.getTime();
		System.out.println("The Java Date is:" + utilDate.toString());

		// Get and display SQL DATE
		java.sql.Date sqlDate = new java.sql.Date(javaTime);
		System.out.println("The SQL DATE is: " + sqlDate.toString());

		// Get and display SQL TIME
		java.sql.Time sqlTime = new java.sql.Time(javaTime);
		System.out.println("The SQL TIME is: " + sqlTime.toString());
		
		// Get and display SQL TIMESTAMP
		java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(javaTime);
		System.out.println("The SQL TIMESTAMP is: " + sqlTimestamp.toString());
	}
}

		
		
			The Java Date is:Thu Aug 24 16:51:57 CST 2017
			The SQL DATE is: 2017-08-24
			The SQL TIME is: 16:51:57
			The SQL TIMESTAMP is: 2017-08-24 16:51:57.234
		

1.4.3.1. SimpleDateFormat

				public static void main(String[] args) {

				DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				//get current date time with Date()
				Date date = new Date();
				System.out.println(dateFormat.format(date));

				//get current date time with Calendar()
				Calendar cal = Calendar.getInstance();
				System.out.println(dateFormat.format(cal.getTime()));

				}
			

1.4.3.2. Timestamp

				Timestamp timestamp = new Timestamp(System.currentTimeMillis());

				Date date = new Date();
				Timestamp timestamp = new Timestamp(date.getTime());
			

1.4.3.3. TimeZone

				package cn.netkiller.example;

				import java.sql.Timestamp;
				import java.text.SimpleDateFormat;
				import java.util.Calendar;
				import java.util.Date;
				import java.util.GregorianCalendar;
				import java.util.TimeZone;

				public class TimeZoneTest {

				public TimeZoneTest() {
				// TODO Auto-generated constructor stub
				}

				public static void main(String[] args) {
				// TODO Auto-generated method stub

				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				TimeZone timeZone = TimeZone.getTimeZone("Asia/Harbin");

				Date date = new Date();
				Timestamp timestamp = new Timestamp(date.getTime());

				System.out.println(timestamp);

				timestamp.setHours(timestamp.getHours()+8);
				System.out.println(timestamp);

				simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
				System.out.println(simpleDateFormat.format(date));

				simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Harbin"));
				System.out.println(simpleDateFormat.format(date));

				Calendar calendar = new GregorianCalendar();
				calendar.setTime(date);
				calendar.setTimeZone(timeZone);
				System.out.println(simpleDateFormat.format(calendar.getTime()));
				}

				}
			

1.4.3.4. String to Date

			
package cn.netkiller.example;

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

public class StringToDate {

	public StringToDate() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = "2008-8-8 8:8:8";

		try {

			Date date = formatter.parse(dateString);
			System.out.println(date);
			System.out.println(formatter.format(date));

		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

}			
			
			

1.4.3.5. 比較兩個日期與時間

			
package cn.netkiller.example;

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

public class DateCompare {

	public DateCompare() {
		// TODO Auto-generated constructor stub
	}

	public void fun1() throws InterruptedException {
		Date d1 = new Date();
		Thread.sleep(5000);
		Date d2 = new Date();
		if (d1.before(d2)) {
			System.out.println(String.format("%s < %s", d1.toString(), d2.toString()));
		} else {
			System.out.println(String.format("%s > %s", d1.toString(), d2.toString()));
		}
		if (d2.after(d1)) {
			System.out.println(String.format("%s > %s", d2.toString(), d1.toString()));
		}

		System.out.println(String.format("%s : %s => %d", d2.toString(), d1.toString(), d1.compareTo(d2)));
		System.out.println(String.format("%s : %s => %d", d1.toString(), d2.toString(), d2.compareTo(d1)));
	}

	public void fun2() throws InterruptedException {

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date date1 = new Date();
		Date date2 = new Date();
		String s1 = dateFormat.format(date1);
		String s2 = dateFormat.format(date2);
		System.out.println(String.format("%s : %s => %d", s1, s2, s1.compareTo(s2)));

		date1 = new Date();
		Thread.sleep(5000);
		date2 = new Date();
		s1 = dateFormat.format(date1);
		s2 = dateFormat.format(date2);
		System.out.println(String.format("%s : %s => %d", s1, s2, s1.compareTo(s2)));
		System.out.println(String.format("%s : %s => %d", s2, s1, s2.compareTo(s1)));
		System.out.println();
	}

	public void fun3() throws InterruptedException, ParseException {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		//Date time = formatter.parse("2016-09-27 16:29");
		Date time = formatter.parse("2016-08-09 09:15");
		Date startDate = formatter.parse("2016-08-09 09:15");
		Date endDate = formatter.parse("2016-09-27 16:30");
		
		if (time.before(startDate) || time.after(endDate)) {
			System.out.println("Skip");
		}
	}

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		DateCompare dateCompare = new DateCompare();
		dateCompare.fun1();
		System.out.println();
		dateCompare.fun2();
		System.out.println();
		dateCompare.fun3();
	}

}
			
			

1.4.3.6. Calendar

				
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH )+1;
		
		System.out.println(year + "年 " + month + "月");
			
			

1.4.3.7. getToday

			
	public Date getToday(String time) {
		final Calendar cal = Calendar.getInstance();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd " + time);
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = fmt.parse(dateFormat.format(cal.getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	private Date addOneDay(Date date, int day) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, day);
		return cal.getTime();
	}
			
			

1.4.3.8. Yesterday

					
package cn.netkiller.date;

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

public class Yesterday {

	public Yesterday() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Yesterday yesterday = new Yesterday();
		System.out.println(yesterday.yesterday());
		System.out.println(yesterday.getYesterday("00:00:00"));
		System.out.println(yesterday.getYesterday("23:59:59"));
	}
	private Date yesterday() {
	    final Calendar cal = Calendar.getInstance();
	    cal.add(Calendar.DATE, -1);
	    return cal.getTime();
	}

	private Date getYesterday(String time) {
	        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd "+time);
	        
	        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        Date date = null;
	        try {
	            date = fmt.parse(dateFormat.format(yesterday()));
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	        return date;
	}
}
		

			

1.4.3.9. ISO 8601

			
ISO 8601擴展格式 YYYY-MM-DDTHH:mm:ss.sssZ
			
			

1.4.4. Array

String to Array

		
package cn.netkiller.java;

public class StringToArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="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";
		String[] array = null;   
		array = str.split(",");
		for(int i=0; i<array.length; i++){
			System.out.println(array[i]);
		}
	}
}		
		
		

1.4.4.1. for each

			
	public static void main(String[] args) {
		try {
			
			for (String arg : args) {
				System.out.println(arg);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}			
			
			

1.4.4.2. Array to String

			
package cn.netkiller.java;

import java.util.Arrays;

public class ArrayToString {

	public static void main(String[] args) {
		String[] array = {"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"};
		System.out.println(Arrays.toString(array));
		System.out.println(Arrays.toString(array).replaceAll(", |\\[|\\]", ""));
	}

}
			
			

1.4.5. float

float 不能直接做減法運算

			float a = 77.22f;
			float b = 77.2f;

			System.out.println((float)a-b);
			System.out.println((float)a+b);

			輸出結果為:
			0.020004272
			154.42
		

		
package cn.netkiller.example;

import java.math.BigDecimal;

public class Math {

	public Math() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {

		float a = 77.22f;
		float b = 77.2f;

		System.out.println((float) a + b);
		System.out.println((float) a - b);
		System.out.println((float) a * b);
		System.out.println((float) a / b);

		System.out.println("-------------");

		System.out.println(add(a, b));
		System.out.println(sub(a, b));
		System.out.println(mul(a, b));
		System.out.println(div(a, b));

	}

	public static float add(float v1, float v2) {
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.add(b2).floatValue();
	}

	public static float sub(float v1, float v2) {
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.subtract(b2).floatValue();
	}

	public static float mul(float v1, float v2) {
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.multiply(b2).floatValue();
	}

	public static float div(float v1, float v2) {
		return div(v1, v2, 5);
	}

	public static float div(float v1, float v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue();
	}

	public static float round(float v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Float.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue();
	}
}

		
		

1.4.6. double

		
package cn.netkiller.example;

import java.math.BigDecimal;

public class Math {

	public Math() {
		// TODO Auto-generated constructor stub
	}

	public static double add(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.add(b2).doubleValue();
	}

	public static double sub(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.subtract(b2).doubleValue();
	}

	public static double mul(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	public static double div(double v1, double v2) {
		return div(v1, v2, 8);
	}

	public static double div(double v1, double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
}		
		
		

1.4.7. BigDecimal

		
package cn.netkiller.example;

import java.math.BigDecimal;

public class BigDecimalTest {

	public BigDecimalTest() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BigDecimal first = new BigDecimal("1.0");
		BigDecimal second = new BigDecimal("1.77");
		System.out.println(String.format("%s, %s", first, second));

		if (first.equals(second))

			System.out.println("equals: true");

		else

			System.out.println("equals: false");

		if (first.compareTo(second) == 0)

			System.out.println("compareTo: true");
		else
			System.out.println("compareTo: false");

		BigDecimal zero = new BigDecimal("0");
		BigDecimal one = new BigDecimal("1");
		BigDecimal minus = new BigDecimal("-1");

		if (zero.compareTo(one) < 0)

			System.out.println("比較演算子[ <  ]: true");

		if (one.compareTo(one) == 0)

			System.out.println("比較演算子[ == ]: true");

		if (zero.compareTo(minus) > 0)

			System.out.println("比較演算子[ >  ]: true");

		if (zero.compareTo(minus) >= 0)

			System.out.println("比較演算子[ >= ]: true");

		if (zero.compareTo(minus) != 0)

			System.out.println("比較演算子[ != ]: true");

		if (zero.compareTo(one) <= 0)
			System.out.println("比較演算子[ <= ]: true");

	}

}
		
		

1.4.7.1. Convert BigDecimal Object to double value

			
BigDecimal.doubleValue()
			
			

1.4.8. enum

			class EnumExample1{

			public enum Season { WINTER, SPRING, SUMMER, FALL }

			public static void main(String[] args) {
			for (Season s : Season.values())
			System.out.println(s);
			}
			}