Java Java jtable方法

tblTable.setAutoCreateRowSorter(true); //will make the colums sortable
tblTable.setCellSelectionEnabled(false); //will diable the selection of single cells
tblTable.setRowSelectionAllowed(true); //set it so that when you click a row, the entire row will be selected
tblTable.setColumnSelectionAllowed(false); //set it so that you can't select entire columns
tblTable.getTableHeader().setReorderingAllowed(false); //disable the changing of column positions

Java 检查java中字符串中的数值

java.util.regex.Pattern.matches("\\d*", (test==null)?"":test.trim())

returns a boolean

Java 在Android 1.5上处理Shake事件

package com.gedankentank.android.sensor;

import java.util.List;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class AccelerometerListener implements SensorEventListener {
	
	private SensorManager sensorManager;
	private List<Sensor> sensors;
	private Sensor sensor;
	private long lastUpdate = -1;
	private long currentTime = -1;
	
	private float last_x, last_y, last_z;
	private float current_x, current_y, current_z, currenForce;
	private static final int FORCE_THRESHOLD = 900;
	private final int DATA_X = SensorManager.DATA_X;
	private final int DATA_Y = SensorManager.DATA_Y;
	private final int DATA_Z = SensorManager.DATA_Z;
	
	public AccelerometerListener(Activity parent) {
		SensorManager sensorService = (SensorManager) parent.getSystemService(Context.SENSOR_SERVICE);
		this.sensorManager = sensorManager;
		this.subscriber = subscriber;
		this.sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
		if (sensors.size() > 0) {
            sensor = sensors.get(0);
        }
	}
	public void start () {
		if (sensor!=null)  {
			sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
		}
	}
	
	public void stop () {
		sensorManager.unregisterListener(this);
	}
	
	public void onAccuracyChanged(Sensor s, int valu) {
		
		
	}
	public void onSensorChanged(SensorEvent event) {
		
		if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER || event.values.length < 3)
		      return;
		
		currentTime = System.currentTimeMillis();
		
		if ((currentTime - lastUpdate) > 100) {
			long diffTime = (currentTime - lastUpdate);
			lastUpdate = currentTime;
			
			current_x = event.values[DATA_X];
			current_y = event.values[DATA_Y];
			current_z = event.values[DATA_Z];
			
			currenForce = Math.abs(current_x+current_y+current_z - last_x - last_y - last_z) / diffTime * 10000;
			
			if (currenForce > FORCE_THRESHOLD) {
			
				// Device has been shaken now go on and do something
				// you could now inform the parent activity ...
				
			}
			last_x = current_x;
			last_y = current_y;
			last_z = current_z;

		}
	}

}

Java 独生子

public class Singleton {  
  
  static class SingletonHolder {  
    static Singleton instance = new Singleton();  
  }  
  
  public static Singleton getInstance() {  
    return SingletonHolder.instance;  
  }  
  
}

Java 确定Android中是否存在Intent Receiver

/**
 * Indicates whether the specified action can be used as an intent. This
 * method queries the package manager for installed packages that can
 * respond to an intent with the specified action. If no suitable package is
 * found, this method returns false.
 *
 * @param context The application's environment.
 * @param action The Intent action to check for availability.
 *
 * @return True if an Intent with the specified action can be sent and
 *         responded to, false otherwise.
 */
public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

Java AES加密/解密器,使用JCE在Java中检入CFB模式

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Cryptor {
	private static byte[] r = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6,
			0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };
	private static byte[] header = new byte[] { 0x1, 0x2, 0x2 };
	private static int headerlen = 3;
	private static byte[] iv = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6,
			0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };
	private static int shalen = 32;

	private SecretKeySpec secretKeySpec = new SecretKeySpec(r, "AES");
	private IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

	public byte[] encrypt(String plaintext) throws IOException,
			NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, InvalidAlgorithmParameterException,
			IllegalBlockSizeException, BadPaddingException {
		byte[] text = plaintext.getBytes();

		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		stream.write(header);

		// Encrypt text
		Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
		cipher.init(Cipher.ENCRYPT_MODE, this.secretKeySpec,
				this.ivParameterSpec);
		stream.write(cipher.doFinal(text));

		// Hash text
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		digest.update(text);
		stream.write(digest.digest());

		byte[] bytes = stream.toByteArray();
		stream.close();
		return bytes;
	}

	public String decrypt(byte[] bytes) throws NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException,
			BadPaddingException, InvalidHashException, InvalidHeaderException {
		ByteBuffer buf = ByteBuffer.wrap(bytes);

		byte[] header = new byte[headerlen];
		buf.get(header);
		if (!Arrays.equals(header, Cryptor.header))
			throw new InvalidHeaderException(
					"Header is not valid. Decryption aborted.");

		int aeslen = bytes.length - shalen - headerlen;
		byte[] aes = new byte[aeslen];
		buf.get(aes);

		// Decrypt text
		Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
		cipher.init(Cipher.DECRYPT_MODE, this.secretKeySpec,
				this.ivParameterSpec);
		byte[] text = cipher.doFinal(aes);

		// Compute hash
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		digest.update(text);
		byte[] hash = digest.digest();

		byte[] hash2 = new byte[shalen];
		buf.get(hash2);

		if (!Arrays.equals(hash, hash2))
			throw new InvalidHashException(
					"Verification failed. Decryption aborted.");

		return new String(text);
	}

	class InvalidHeaderException extends Exception {
		private static final long serialVersionUID = 1L;

		public InvalidHeaderException(String string) {
			super(string);
		}
	}

	class InvalidHashException extends Exception {
		private static final long serialVersionUID = 1L;

		public InvalidHashException(String string) {
			super(string);
		}
	}

	public static void main(String[] args) throws Exception {
		Cryptor c = new Cryptor();

		System.out
				.println(c
						.decrypt(c
								.encrypt("String encryption/decryption with integrity check. In a real world example, the key should be kept secret and the IV should be unique.")));

	}

}

Java 迭代Freemarker中的地图

<#list map?keys as key>
    ${key} - ${map[key]}
</#list>

Java Java“Hello World”

// File:	Hello.java
// Purpose:	Print a message on the screen
// Listing:	Chapter 1, Listing 1.1
public class Hello {
	public static void main(String[] args) {
		System.out.println("hello, world"); 
	}
}

Java 复制到剪贴板

Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
                    ImageTransferable imageTrans = new ImageTransferable(bufferImage);
                    clip.setContents(imageTrans, null);

Java JavaScript代理的JavaScript代理

<%@page session="false"%>
<%@page import="java.net.*,java.io.*" %>
<%
try {
	String reqUrl = request.getQueryString();
	
	URL url = new URL(reqUrl);
	HttpURLConnection con = (HttpURLConnection)url.openConnection();
	con.setDoOutput(true);
	con.setRequestMethod(request.getMethod());
	int clength = request.getContentLength();
	if(clength > 0) {
		con.setDoInput(true);
		byte[] idata = new byte[clength];
		request.getInputStream().read(idata, 0, clength);
		con.getOutputStream().write(idata, 0, clength);
	}
	response.setContentType(con.getContentType());

	BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
	String line;
	while ((line = rd.readLine()) != null) {
		out.println(line); 
	}
	rd.close();

} catch(Exception e) {
	response.setStatus(500);
}
%>