@@ -0,0 +1,178 @@
package cn.zach.image;


import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
* 图片工具类, 图片水印,文字水印,缩放,补白等
* @author Carl He
*/
public final class ImageUtils {
/**图片格式:JPG*/
private static final String PICTRUE_FORMATE_JPG = "jpg";

private ImageUtils(){}
/**
* 添加图片水印
* @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
* @param waterImg 水印图片路径,如:C://myPictrue//logo.png
* @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public final static void pressImage(String targetImg, String waterImg, int x, int y, float alpha) {
try {
File file = new File(targetImg);
Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);

Image waterImage = ImageIO.read(new File(waterImg)); // 水印文件
int width_1 = waterImage.getWidth(null);
int height_1 = waterImage.getHeight(null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

int widthDiff = width - width_1;
int heightDiff = height - height_1;
if(x < 0){
x = widthDiff / 2;
}else if(x > widthDiff){
x = widthDiff;
}
if(y < 0){
y = heightDiff / 2;
}else if(y > heightDiff){
y = heightDiff;
}
g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
g.dispose();
ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 添加文字水印
* @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
* @param pressText 水印文字, 如:中国证券网
* @param fontName 字体名称, 如:宋体
* @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
* @param fontSize 字体大小,单位为像素
* @param color 字体颜色
* @param x 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public static void pressText(String targetImg, String pressText, String fontName, int fontStyle, int fontSize, Color color, int x, int y, float alpha) {
try {
File file = new File(targetImg);

Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.setFont(new Font(fontName, fontStyle, fontSize));
g.setColor(color);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

int width_1 = fontSize * getLength(pressText);
int height_1 = fontSize;
int widthDiff = width - width_1;
int heightDiff = height - height_1;
if(x < 0){
x = widthDiff / 2;
}else if(x > widthDiff){
x = widthDiff;
}
if(y < 0){
y = heightDiff / 2;
}else if(y > heightDiff){
y = heightDiff;
}

g.drawString(pressText, x, y + height_1);
g.dispose();
ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 获取字符长度,一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
* @param text
* @return 字符长度,如:text="中国",返回 2;text="test",返回 2;text="中国ABC",返回 4.
*/
public static int getLength(String text) {
int textLength = text.length();
int length = textLength;
for (int i = 0; i < textLength; i++) {
if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
length++;
}
}
return (length % 2 == 0) ? length / 2 : length / 2 + 1;
}

/**
* 图片缩放
* @param filePath 图片路径
* @param height 高度
* @param width 宽度
* @param bb 比例不对时是否需要补白
*/
public static void resize(String filePath, int height, int width, boolean bb) {
try {
double ratio = 0; //缩放比例
File f = new File(filePath);
BufferedImage bi = ImageIO.read(f);
Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
//计算比例
if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
if (bi.getHeight() > bi.getWidth()) {
ratio = (new Integer(height)).doubleValue() / bi.getHeight();
} else {
ratio = (new Integer(width)).doubleValue() / bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
itemp = op.filter(bi, null);
}
if (bb) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
if (width == itemp.getWidth(null))
g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
else
g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
g.dispose();
itemp = image;
}
ImageIO.write((BufferedImage) itemp, "jpg", f);
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) throws IOException {
resize("D://jq.jpg", 500, 500, true);
}
}
@@ -0,0 +1,38 @@
package cn.zach.schedule;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest implements Runnable{
private String jobName = "";

public ScheduledExecutorTest(String jobName) {
super();
this.jobName = jobName;
}

@Override
public void run() {
System.out.println("execute " + jobName);
}

public static void main(String[] args){
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

//scheduleAtFiexedRate每次执行时间为上一次任务开始向后推一个时间间隔
//即每次执行时间为initialDelay, initialDelay+period, initialDelay+2*period, …
long initialDelay1 = 1;
long period1 = 1;
service.scheduleAtFixedRate(new ScheduledExecutorTest("job1"), initialDelay1, period1, TimeUnit.SECONDS);

//scheduledWithFixedDelay每次执行时间为上一次任务结束后向后推一个时间间隔
//即每次执行时间为initialDelay, initialDelay+executeTime+delay, initialDelay+2*executeTime+2*delay
long initialDelay2 = 1;
long delay2 = 1;
service.scheduleWithFixedDelay(new ScheduledExecutorTest("job2"), initialDelay2, delay2, TimeUnit.SECONDS);

//ScheduleAtFixedRate 是基于固定时间间隔进行任务调度,ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。
}

}
@@ -0,0 +1,122 @@
package cn.zach.string;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BraceMatch {
/*
*检测给定文件中大小括号是否匹配
*/

public static void main(String[] args) {
File file = new File("D:\\tmp.txt");
try {
BraceMatch.checkBracesByStack(file);
}catch (Exception e) {
e.printStackTrace();
}
}

public static void checkBracesByStack(File file) throws Exception {
//检查文件是否存在
if(!file.exists()) {
System.out.println("文件不存在");
System.exit(1);
}
FileInputStream fis = null;
//模拟一个栈
byte[] stack = new byte[1024];
int length = 0;
//模拟的栈的指针
int index = 0;
int count=0;
byte[] bs = new byte[1024];
try {
fis = new FileInputStream(file);
//当文件未达到结尾时,循环遍历
while((length=fis.read(bs)) != -1) {
count++;
for(int i=0; i<length; i++) {
switch(bs[i]) {
//若是左大括号{,则进栈
//{=123
case 123 :
stack[index] = bs[i];
index ++;
continue;
//若是有大右括号},栈指针向下移动一格,检查栈顶元素是否为左大括号{。
//若是,出栈,并继续遍历 ;若不是,则大括号不匹配,抛出异常
//}=125
case 125 :
if(stack[index-1] != 123) {
System.out.println(count);
System.out.println("index:" + index);
throw new Exception("大括号不匹配!");
}else {
stack[index-1] = 0;
index --;
continue;
}

//若是左中括号[,则进栈
//[=91
case 91 :
stack[index] = bs[i];
index ++;
continue;
//若是有中右括号],栈指针向下移动一格,检查栈顶元素是否为左中括号[。
//若是,出栈,并继续遍历 ;若不是,则中括号不匹配,抛出异常
//]=93
case 93 :
if(stack[index-1] != 91) {
System.out.println(count);
System.out.println("index:" + index);
throw new Exception("中括号不匹配!");
}else {
stack[index-1] = 0;
index --;
continue;
}

//若是左小括号{,则进栈 (=40
case 40 :
stack[index] = bs[i];
index ++;
continue;
//若是有小右括号},栈指针向下移动一格,检查栈顶元素是否为左小括号(。
//若是,出栈,并继续遍历 ;若不是,则括号不匹配,抛出异常
// )=41
case 41 :
if(stack[index-1] != 40) {
System.out.println(count);
System.out.println("index:" + index);
throw new Exception("小括号不匹配!");
}else {
stack[index-1] = 0;
index --;
continue;
}
}
}
}

//文件遍历完成,若栈不为空,则括号不匹配
if(index != 0) {
System.out.println(count);
System.out.println("index:" + index);
throw new Exception("括号不匹配!");
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis != null) {
fis.close();
}
}
}

}
@@ -0,0 +1,16 @@
package cn.zach.string;

public class replaceString {
private static String replaceServerAddrByRealAddr(String serv, String addr) {
//serv = http://10.2.12.76:9999/param/zcgl
int endIndex = serv.substring(7).indexOf(":");
String tails = serv.substring(7+endIndex);
return "http://".concat(addr).concat(tails);
}
public static void main(String[] args){
String serv = "http://10.2.12.76:9999/param/zcgl/";
String addr = "test";
System.out.println(replaceServerAddrByRealAddr(serv, addr));
}

}
@@ -0,0 +1,30 @@
package cn.zach.sysinfo;

import java.util.ArrayList;
import java.util.List;

public class CPU {
public static void main(String[] args){
int DEFAULT_THREADS = Runtime.getRuntime().availableProcessors();
System.out.println("¿ÉÓúËÐÄÊý£º"+DEFAULT_THREADS);

//ÑéÖ¤toArray
List<String> arrList = new ArrayList<String>();
String[] array = {"a"};
for(int i=0;i<array.length;i++){
arrList.add(array[i]);
}
String[] temp = arrList.toArray(new String[0]);
for(int i=0;i<temp.length;i++){
System.out.println(temp[i]);
}
System.out.println(array.length);

//Is null an instance of Object? The answer is No!
if(null instanceof Object){
System.out.println("null is instanceof Object");
}else{
System.out.println("null is not instanceof Object");
}
}
}
@@ -0,0 +1,26 @@
package cn.zach.temp;

//tricky extends interview question
public class Father {

public void print(){
test('a');
}
public void test(int a){
System.out.println("2 Father test(int)");
}
}
class Son extends Father{
public void test(char a){
System.out.println("3 Son test(char)");
}

public void test(int a){
System.out.println("4 Son test(int)");
}

public static void main(String[] args) {
new Son().print();
}

}
@@ -0,0 +1,22 @@
package cn.zach.temp;

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

public class TimeFormat {
public static void main(String[] args){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long time1 = 0,time2 = 0;
try {
time1 = df.parse("2015-08-05 09:50:14").getTime();
time2 = df.parse("2015-08-05 12:50:10").getTime();
} catch (ParseException e) {
e.printStackTrace();
}
long diff = (time2-time1)/1000;
long hour = diff/(60*60);
System.out.println(hour);
System.out.println("helloword".equals(null));
}
}
@@ -0,0 +1,11 @@
package cn.zach.thread;

public class Main {
public static void main(String[] args) throws InterruptedException{
SuchThread wow = new SuchThread("much-name");
wow.run();
wow.sleep(1000);
wow.setName("just another thread name");
wow.run();
}
}
@@ -0,0 +1,11 @@
package cn.zach.thread;

public class SuchThread extends Thread{
public SuchThread(String name) {
super(name);
}

public void run(){
System.out.println("Hi Mom! " + getName());
}
}
@@ -0,0 +1,43 @@
package cn.zach.thread;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static java.util.Arrays.asList;

public class Sums {

static class Sum implements Callable<Long>{

private final long from;
private final long to;

Sum(long from, long to){
this.from = from;
this.to = to;
}

@Override
public Long call() throws Exception {
long acc = 0;
for(long i=from; i<=to; i++){
acc = acc + i;
}
return acc;
}

}

public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Future<Long>> results = executor.invokeAll(asList(new Sum(0, 10), new Sum(100, 1_000), new Sum(10_000, 1_000_000)));
executor.shutdown();

for(Future<Long> result:results){
System.out.println(result.get());
}
}

}