`
mpqi
  • 浏览: 76330 次
  • 性别: Icon_minigender_2
  • 来自: 成都
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
Canvas、Bitmap内存资源回收 android
public class MyView {
    private Canvas mCanvas;
    private Bitmap mBitmap;
    private static Bitmap mFreeBitmap;


    static {
mFreeBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
}


    public MyView(){
        ...
        mBitmap = BitmapFactory.createBitmap(...);
        mCanvas = new Canvas(mBitmap);
        ...
    }


    public void deinit(){
        // 销毁时调用
        if(mBitmap != null && !mBitmap.isRecycled()){
            mCanvas.setBitmap(mFreeBitmap);
            mBitmap.recycle();
            mBitmap = null;
        }
    }
}
Android获取手机和系统版本等信息 android
        String phoneInfo = "Product: " + android.os.Build.PRODUCT;
        phoneInfo += ",\n CPU_ABI: " + android.os.Build.CPU_ABI;
        phoneInfo += ",\n TAGS: " + android.os.Build.TAGS;
        phoneInfo += ",\n VERSION_CODES.BASE: " + android.os.Build.VERSION_CODES.BASE;
        phoneInfo += ",\n MODEL: " + android.os.Build.MODEL;//手机型号
         phoneInfo += ",\n SDK: " + android.os.Build.VERSION.SDK;
        phoneInfo += ",\n VERSION.RELEASE: " + android.os.Build.VERSION.RELEASE;//Android版本
         phoneInfo += ",\n DEVICE: " + android.os.Build.DEVICE;
        phoneInfo += ",\n DISPLAY: " + android.os.Build.DISPLAY;
        phoneInfo += ",\n BRAND: " + android.os.Build.BRAND;
        phoneInfo += ",\n BOARD: " + android.os.Build.BOARD;
        phoneInfo += ",\n FINGERPRINT: " + android.os.Build.FINGERPRINT;
        phoneInfo += ",\n ID: " + android.os.Build.ID;
        phoneInfo += ",\n MANUFACTURER: " + android.os.Build.MANUFACTURER;
        phoneInfo += ",\n USER: " + android.os.Build.USER;        
		TextView Temp_textView = new TextView(this);
		Temp_textView.setText("TEMP:    "+phoneInfo);
		linearLayout.addView(Temp_textView);
生肖,星座,年龄 tool
public static String toShengXiao(int year) {
		  String sxiao = "";
		  int start = 1901;
		  int x = (start - year) % 12;
		  if (x == 1 || x == -11) {
		   sxiao = "鼠";
		  }
		  if (x == 0) {
		   sxiao = "牛";
		  }
		  if (x == 11 || x == -1) {
		   sxiao = "虎";
		  }
		  if (x == 10 || x == -2) {
		   sxiao = "兔";
		  }
		  if (x == 9 || x == -3) {
		   sxiao = "龙";
		  }
		  if (x == 8 || x == -4) {
		   sxiao = "蛇";
		  }
		  if (x == 7 || x == -5) {
		   sxiao = "马";
		  }
		  if (x == 6 || x == -6) {
		   sxiao = "羊";
		  }
		  if (x == 5 || x == -7) {
		   sxiao = "猴";
		  }
		  if (x == 4 || x == -8) {
		   sxiao = "鸡";
		  }
		  if (x == 3 || x == -9) {
		   sxiao = "狗";
		  }
		  if (x == 2 || x == -10) {
		   sxiao = "猪";
		  }
		  return sxiao;
		 }

		 public static String toXingZuo(int month, int day) {
		  String star = "";
		  if (month == 1 && day >= 20 || month == 2 && day <= 18) {
		   star = "水瓶座";
		  }

		  if (month == 2 && day >= 19 || month == 3 && day <= 20) {
		   star = "双鱼座";
		  }

		  if (month == 3 && day >= 21 || month == 4 && day <= 19) {
		   star = "白羊座";
		  }

		  if (month == 4 && day >= 20 || month == 5 && day <= 20) {
		   star = "金牛座";
		  }

		  if (month == 5 && day >= 21 || month == 6 && day <= 21) {
		   star = "双子座";
		  }

		  if (month == 6 && day >= 22 || month == 7 && day <= 22) {
		   star = "巨蟹座";
		  }

		  if (month == 7 && day >= 23 || month == 8 && day <= 22) {
		   star = "狮子座";
		  }

		  if (month == 8 && day >= 23 || month == 9 && day <= 22) {
		   star = "处女座";
		  }

		  if (month == 9 && day >= 23 || month == 10 && day <= 22) {
		   star = "天秤座";
		  }

		  if (month == 10 && day >= 23 || month == 11 && day <= 21) {
		   star = "天蝎座";
		  }

		  if (month == 11 && day >= 22 || month == 12 && day <= 21) {
		   star = "射手座";
		  }

		  if (month == 12 && day >= 22 || month == 1 && day <= 19) {
		   star = "摩羯座";
		  }

		  return star;
		 }

		 public static int toAge(int year) {
		  int age = 0;
		  Date date = new Date();
		  SimpleDateFormat sd = new SimpleDateFormat("yyyy");
		  age = Integer.parseInt(sd.format(date)) - year;
		  return age;
		 }
Android_EditText属性 api, android
android:layout_gravity="center_vertical"//设置控件显示的位置:默认top,这里居中显示,还有bottom

android:hint="请输入数字!"//设置显示在控件上的提示信息,控件上无值时显示

android:numeric="integer"//设置只能输入整数,如果是小数则是:decimal

android:singleLine="true"//设置单行输入,一旦设置为true,则文字不会自动换行。

android:gray="top" //多行中指针在第一行第一位置et.setSelection(et.length());//调整光标到最后一行

android:autoText //自动拼写帮助

android:capitalize //首字母大写

android:digits //设置只接受某些数字

android:singleLine //是否单行或者多行,回车是离开文本框还是文本框增加新行

android:numeric //只接受数字

android:password //密码

android:phoneNumber // 输入电话号码

android:editable //是否可编辑

android:autoLink=”all” //设置文本超链接样式当点击网址时,跳向该网址

android:password="true"//设置只能输入密码

android:textColor = "#ff8c00"//字体颜色

android:textStyle="bold"//字体,bold, italic, bolditalic

android:textSize="20dip"//大小

android:capitalize = "characters"//以大写字母写

android:textAlign="center"//EditText没有这个属性,但TextView有

android:textColorHighlight="#cccccc"//被选中文字的底色,默认为蓝色

android:textColorHint="#ffff00"//设置提示信息文字的颜色,默认为灰色

android:textScaleX="1.5"//控制字与字之间的间距

android:typeface="monospace"//字型,normal, sans, serif, monospace

android:background="@null"//空间背景,这里没有,指透明

android:layout_weight="1"//权重在控制控 件显示的大小时蛮有用的。

android:textAppearance="?android:attr/textAppearanceLargeInverse"//文字外观,这里引用的是系统自带的一个外观,?表示系统是否有这种外观,否则使用默认的外观。
swing进度条 swing
package com.demo.cigm.test;
import   java.awt.*; 
import   java.awt.event.*; 
import   javax.swing.*; 

public   class   ProgressBarTest 
{     public   static   void   main(String[]   args) 
      {     JFrame   frame   =   new   ProgressBarFrame(); 
            frame.show(); 
      } 
} 

class   ProgressBarFrame   extends   JFrame 
{
	private   Timer   activityMonitor; 
    private   JButton   startButton; 
    private   JProgressBar   progressBar; 
    private   JTextArea   textArea; 
    private   SimulatedActivity   activity; 
    
    
	public   ProgressBarFrame() 
      {     setTitle( "ProgressBarTest "); 
            setSize(300,   200); 
            addWindowListener(new   WindowAdapter() 
                  {     public   void   windowClosing(WindowEvent   e) 
                        {     System.exit(0); 
                        } 
                  }   ); 

            Container   contentPane   =   getContentPane(); 

            //   this   text   area   holds   the   activity   output 
            textArea   =   new   JTextArea(); 

            //   set   up   panel   with   button   and   progress   bar 

            JPanel   panel   =   new   JPanel(); 
            startButton   =   new   JButton( "Start "); 
            progressBar   =   new   JProgressBar(); 
            progressBar.setStringPainted(true); 
            panel.add(startButton); 
            panel.add(progressBar); 
            contentPane.add(new   JScrollPane(textArea),   "Center"); 
            contentPane.add(panel,   "South"); 

            //   set   up   the   button   action 

            startButton.addActionListener( 
                  new   ActionListener() 
                        {     public   void   actionPerformed(ActionEvent   event) 
                              {     progressBar.setMaximum(1000); 
                                    activity   =   new   SimulatedActivity(1000); 
                                    activity.start(); 
                                    activityMonitor.start(); 
                                    startButton.setEnabled(false); 
                              } 
                        }); 


            //   set   up   the   timer   action 

            activityMonitor   =   new   Timer(500, 
                  new   ActionListener() 
                        {     public   void   actionPerformed(ActionEvent   event) 
                              {     int   current   =   activity.getCurrent(); 

                                    //   show   progress 
                                    textArea.append(current   +   "\n "); 
                                    progressBar.setValue(current); 

                                    //   check   if   task   is   completed 
                                    if   (current   ==   activity.getTarget()) 
                                    {     activityMonitor.stop(); 
                                          startButton.setEnabled(true); 
                                    } 
                              } 
                        }); 
      } 

      
} 

class   SimulatedActivity   extends   Thread 
{     public   SimulatedActivity(int   t) 
      {     current   =   0; 
            target   =   t; 
      } 

      public   int   getTarget() 
      {     return   target; 
      } 

      public   int   getCurrent() 
      {     return   current; 
      } 

      public   void   run() 
      {     while   (current   <   target   &&   !interrupted()) 
            {     try 
                  {     sleep(100); 
                  } 
                  catch(InterruptedException   e) 
                  {     return; 
                  } 
                  current++; 
            } 
      } 

      private   int   current; 
      private   int   target; 
}
spring直接获得bean spring
		ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
		OperationExamineService  oa= (OperationExamineService) ac.getBean("operationExamineService");
		System.out.println(oa);
时间格式转换 tool
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DecimalFormatUtil { 
	
	/**浮点数四舍五入*/
	public static Double DoubleFormat(Double double1) {
		DecimalFormat df = new DecimalFormat( "0.00 ");
		return Double.valueOf(df.format(double1));
	}
	
	/** 把Date类型的数据转化为时间字符串*/
	//(从数据库中取出)
	public static String toStOnlyTime(Date date) {
		String time;
		SimpleDateFormat forma=new SimpleDateFormat();
		forma.applyPattern("HH:mm:ss");
		time=forma.format(date);
		return time;
	}
	
	/** 把Date类型的数据转化为日期+时间字符串*/
	//(从数据库中取出)
	public static String toStTime(Date date) {
		String time;
		SimpleDateFormat forma=new SimpleDateFormat();
		forma.applyPattern("yyyy-MM-dd HH:mm:ss");
		time=forma.format(date);
		return time;
	}

	/** 把日期+时间字符串转化为Date类型的数据*/
	//(输入到数据库中)
	public static Date toDateTime(String sdate) {
		Date date = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		try {
			date = format.parse(sdate);		   
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}
	
	/** 把Date类型的数据转化为日期字符串*/
	//(从数据库中取出)
	public static String toSt(Date date) {
		String time;
		SimpleDateFormat forma=new SimpleDateFormat();
		forma.applyPattern("yyyy-MM-dd");
		time=forma.format(date);
		return time;
	}

	/** 把日期字符串转化为Date类型的数据*/
	//(输入到数据库中)
	public static Date toDate(String sdate) {
		Date date = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		try {
			date = format.parse(sdate);		   
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}

}
Base64编码解码 tool
package com.xinxin.cigm.util;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

public class Base64 {
	private static char[] base64EncodeChars = new char[] { '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', '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', '0', '1', '2', '3',
			'4', '5', '6', '7', '8', '9', '+', '/' };

	private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
			-1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
			60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
			10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
			-1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
			38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
			-1, -1 };

	private Base64() {
	}

	public static String encode(byte[] data) {
		StringBuffer sb = new StringBuffer();
		int len = data.length;
		int i = 0;
		int b1, b2, b3;

		while (i < len) {
			b1 = data[i++] & 0xff;
			if (i == len) {
				sb.append(base64EncodeChars[b1 >>> 2]);
				sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
				sb.append("==");
				break;
			}
			b2 = data[i++] & 0xff;
			if (i == len) {
				sb.append(base64EncodeChars[b1 >>> 2]);
				sb.append(base64EncodeChars[((b1 & 0x03) << 4)
						| ((b2 & 0xf0) >>> 4)]);
				sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
				sb.append("=");
				break;
			}
			b3 = data[i++] & 0xff;
			sb.append(base64EncodeChars[b1 >>> 2]);
			sb.append(base64EncodeChars[((b1 & 0x03) << 4)
					| ((b2 & 0xf0) >>> 4)]);
			sb.append(base64EncodeChars[((b2 & 0x0f) << 2)
					| ((b3 & 0xc0) >>> 6)]);
			sb.append(base64EncodeChars[b3 & 0x3f]);
		}
		return sb.toString();
	}

	public static byte[] decode(String str) {
		byte[] data = str.getBytes();
		int len = data.length;
		ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
		int i = 0;
		int b1, b2, b3, b4;

		while (i < len) {

			/* b1 */
			do {
				b1 = base64DecodeChars[data[i++]];
			} while (i < len && b1 == -1);
			if (b1 == -1) {
				break;
			}

			/* b2 */
			do {
				b2 = base64DecodeChars[data[i++]];
			} while (i < len && b2 == -1);
			if (b2 == -1) {
				break;
			}
			buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

			/* b3 */
			do {
				b3 = data[i++];
				if (b3 == 61) {
					return buf.toByteArray();
				}
				b3 = base64DecodeChars[b3];
			} while (i < len && b3 == -1);
			if (b3 == -1) {
				break;
			}
			buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

			/* b4 */
			do {
				b4 = data[i++];
				if (b4 == 61) {
					return buf.toByteArray();
				}
				b4 = base64DecodeChars[b4];
			} while (i < len && b4 == -1);
			if (b4 == -1) {
				break;
			}
			buf.write((int) (((b3 & 0x03) << 6) | b4));
		}
		return buf.toByteArray();
	}

	public  static String dec(String json)
	{
		try {
			return new String(decode(json),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
}
安卓USB通讯_手机端service android, usb
package com.xinxin.cigm.forms;  
  
import java.io.File;  
import java.io.IOException;  
import java.net.ServerSocket;  
import java.net.Socket;  

import com.xinxin.cigm.forms.com.otheri.service.ThreadReadWriterIOSocket;
  
import android.app.Service;  
import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.content.IntentFilter;  
import android.os.IBinder;  
import android.util.Log;  
  
/** 
 * 设置:android手机 
 *  
 *  
 * */  
public class androidService extends Service {  
    public static final String TAG = "TAG";  
    public static Boolean mainThreadFlag = true;  
    public static Boolean ioThreadFlag = true;  
    ServerSocket serverSocket = null;  
    final int SERVER_PORT = 10086;  
    File testFile;  
    private sysBroadcastReceiver sysBR;  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Log.v(TAG, Thread.currentThread().getName() + "---->" + "  onCreate");  
        /* 创建内部类sysBroadcastReceiver 并注册registerReceiver */  
        sysRegisterReceiver();  
        Thread thread = new Thread(new Runnable() {
			public void run() {
				 doListen();  
			}
		});
        thread.start();
    }  
  
    private void doListen() {  
        Log.d(TAG, Thread.currentThread().getName() + "---->"  
                + " doListen() START");  
        serverSocket = null;  
        try {  
            Log.d(TAG, Thread.currentThread().getName() + "---->"  
                    + " doListen() new serverSocket");  
            serverSocket = new ServerSocket(SERVER_PORT);  
  
            boolean mainThreadFlag = true;  
            while (mainThreadFlag) {  
                Log.d(TAG, Thread.currentThread().getName() + "---->"  
                        + " doListen() listen");  
  
                Socket client = serverSocket.accept();  
  
                new Thread(new ThreadReadWriterIOSocket(this, client)).start();  
            }  
        } catch (IOException e1) {  
            Log.v(androidService.TAG, Thread.currentThread().getName()  
                    + "---->" + "new serverSocket error");  
            e1.printStackTrace();  
        }  
    }  
  
    /* 创建内部类sysBroadcastReceiver 并注册registerReceiver */  
    private void sysRegisterReceiver() {  
        Log.v(TAG, Thread.currentThread().getName() + "---->"  
                + "sysRegisterReceiver");  
        sysBR = new sysBroadcastReceiver();  
        /* 注册BroadcastReceiver */  
        IntentFilter filter1 = new IntentFilter();  
        /* 新的应用程序被安装到了设备上的广播 */  
        filter1.addAction("android.intent.action.PACKAGE_ADDED");  
        filter1.addDataScheme("package");  
        filter1.addAction("android.intent.action.PACKAGE_REMOVED");  
        filter1.addDataScheme("package");  
        registerReceiver(sysBR, filter1);  
    }  
  
    /* 内部类:BroadcastReceiver 用于接收系统事件 */  
    private class sysBroadcastReceiver extends BroadcastReceiver {  
  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            if (action.equalsIgnoreCase("android.intent.action.PACKAGE_ADDED")) {  
                // ReadInstalledAPP();   
            } else if (action  
                    .equalsIgnoreCase("android.intent.action.PACKAGE_REMOVED")) {  
                // ReadInstalledAPP();   
            }  
            Log.v(TAG, Thread.currentThread().getName() + "---->"  
                    + "sysBroadcastReceiver onReceive");  
        }  
    }  
  
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
  
        // 关闭线程   
        mainThreadFlag = false;  
        ioThreadFlag = false;  
        // 关闭服务器   
        try {  
            Log.v(TAG, Thread.currentThread().getName() + "---->"  
                    + "serverSocket.close()");  
            serverSocket.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        Log.v(TAG, Thread.currentThread().getName() + "---->"  
                + "**************** onDestroy****************");  
    }  
  
    @Override  
    public void onStart(Intent intent, int startId) {  
        Log.d(TAG, Thread.currentThread().getName() + "---->" + " onStart()");  
        super.onStart(intent, startId);  
  
    }  
  
    @Override  
    public IBinder onBind(Intent arg0) {  
        Log.d(TAG, "  onBind");  
        return null;  
    }  
  
}
安卓USB通讯_PC端 android, usb
package com.xinxin.cimg;


import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.BufferedReader;  
import java.io.IOException;
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.net.InetAddress;  
import java.net.Socket;  
import java.net.UnknownHostException;  

public class Client {
	  
	    /** 
	     * @param args 
	     * @throws InterruptedException 
	     */  
	    public static void main(String[] args) throws InterruptedException {  
	        try {  
	            Runtime.getRuntime().exec(  
	                    "adb shell am broadcast -a NotifyServiceStop");  
	            Thread.sleep(3000);  
	            Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086");  
	            Thread.sleep(3000);  
	            Runtime.getRuntime().exec(  
	                    "adb shell am broadcast -a NotifyServiceStart");  
	            Thread.sleep(3000);  
	        } catch (IOException e3) {  
	            e3.printStackTrace();  
	        }  
	  
	        Socket socket = null;  
	        try {  
	            InetAddress serverAddr = null;  
	            serverAddr = InetAddress.getByName("127.0.0.1");  
	            System.out.println("TCP 1111" + "C: Connecting...");  
	            socket = new Socket(serverAddr, 12580);  
	            String str = "hi,wufenglong";  
	            System.out.println("TCP 221122" + "C:RECEIVE");  
	            BufferedOutputStream out = new BufferedOutputStream(socket  
	                    .getOutputStream());  
	            BufferedInputStream in = new BufferedInputStream(socket  
	                    .getInputStream());  
	            BufferedReader br = new BufferedReader(new InputStreamReader(  
	                    System.in));  
	            boolean flag = true;  
	            while (flag) {  
	                System.out.print("请输入1~6的数字,退出输入exit:");  
	                String strWord = br.readLine();// 从控制台输入1~6   
	                if (strWord.equals("1")) {  
	                    out.write("1".getBytes());  
	                    out.flush();  
	                    System.out.println("1 finish sending the data");  
	                    String strFormsocket = readFromSocket(in);  
	                    System.out.println("the data sent by server is:/r/n"  
	                            + strFormsocket);  
	                    System.out  
	                            .println("=============================================");  
	                } else if (strWord.equals("2")) {  
	                    out.write("2".getBytes());  
	                    out.flush();  
	                    System.out.println("2 finish sending the data");  
	                    String strFormsocket = readFromSocket(in);  
	                    System.out.println("the data sent by server is:/r/n"  
	                            + strFormsocket);  
	                    System.out  
	                            .println("=============================================");  
	                } else if (strWord.equals("3")) {  
	                    out.write("3".getBytes());  
	                    out.flush();  
	                    System.out.println("3 finish sending the data");  
	                    String strFormsocket = readFromSocket(in);  
	                    System.out.println("the data sent by server is:/r/n"  
	                            + strFormsocket);  
	                    System.out  
	                            .println("=============================================");  
	                } else if (strWord.equals("4")) {  
	                    /* 发送命令 */  
	                    out.write("4".getBytes());  
	                    out.flush();  
	                    System.out.println("send file finish sending the CMD:");  
	                    /* 服务器反馈:准备接收 */  
	                    String strFormsocket = readFromSocket(in);  
	                    System.out  
	                            .println("service ready receice data:UPDATE_CONTACTS:"  
	                                    + strFormsocket);  
	                    byte[] filebytes = FileHelper.readFile("R0013340.JPG");  
	                    System.out.println("file size=" + filebytes.length);  
	                    /* 将整数转成4字节byte数组 */  
	                    byte[] filelength = new byte[4];  
	                    filelength = tools.intToByte(filebytes.length);  
	                    /* 将.apk字符串转成4字节byte数组 */  
	                    byte[] fileformat = null;  
	                    fileformat = ".apk".getBytes();  
	                    System.out  
	                            .println("fileformat length=" + fileformat.length);  
	                    /* 字节流中前4字节为文件长度,4字节文件格式,以后是文件流 */  
	                    /* 注意如果write里的byte[]超过socket的缓存,系统自动分包写过去,所以对方要循环写完 */  
	                    out.write(filelength);  
	                    out.flush();  
	                    String strok1 = readFromSocket(in);  
	                    System.out.println("service receive filelength :" + strok1);  
	                    // out.write(fileformat);   
	                    // out.flush();   
	                    // String strok2 = readFromSocket(in);   
	                    // System.out.println("service receive fileformat :" +   
	                    // strok2);   
	                    System.out.println("write data to android");  
	                    out.write(filebytes);  
	                    out.flush();  
	                    System.out.println("*********");  
	  
	                    /* 服务器反馈:接收成功 */  
	                    String strread = readFromSocket(in);  
	                    System.out.println(" send data success:" + strread);  
	                    System.out  
	                            .println("=============================================");  
	                } else if (strWord.equalsIgnoreCase("EXIT")) {  
	                    out.write("EXIT".getBytes());  
	                    out.flush();  
	                    System.out.println("EXIT finish sending the data");  
	                    String strFormsocket = readFromSocket(in);  
	                    System.out.println("the data sent by server is:/r/n"  
	                            + strFormsocket);  
	                    flag = false;  
	                    System.out  
	                            .println("=============================================");  
	                }  
	            }  
	  
	        } catch (UnknownHostException e1) {  
	            System.out.println("TCP 331133" + "ERROR:" + e1.toString());  
	        } catch (Exception e2) {  
	            System.out.println("TCP 441144" + "ERROR:" + e2.toString());  
	        } finally {  
	            try {  
	                if (socket != null) {  
	                    socket.close();  
	                    System.out.println("socket.close()");  
	                }  
	            } catch (IOException e) {  
	                System.out.println("TCP 5555" + "ERROR:" + e.toString());  
	            }  
	        }  
	    }  
	  
	    /* 从InputStream流中读数据 */  
	    public static String readFromSocket(InputStream in) {  
	        int MAX_BUFFER_BYTES = 4000;  
	        String msg = "";  
	        byte[] tempbuffer = new byte[MAX_BUFFER_BYTES];  
	        try {  
	            int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);  
	            msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");  
	  
	            tempbuffer = null;  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        // Log.v(Service139.TAG, "msg=" + msg);   
	        return msg;  
	    }  
	}
安卓USB通讯_手机端util_MyUtil android, usb
package com.xinxin.cigm.forms.com.otheri.util;  
  
public class MyUtil {  
    /* byte[]转Int */  
    public static int bytesToInt(byte[] bytes) {  
        int addr = bytes[0] & 0xFF;  
        addr |= ((bytes[1] << 8) & 0xFF00);  
        addr |= ((bytes[2] << 16) & 0xFF0000);  
        addr |= ((bytes[3] << 24) & 0xFF000000);  
        return addr;  
    }  
  
    /* Int转byte[] */  
    public static byte[] intToByte(int i) {  
        byte[] abyte0 = new byte[4];  
        abyte0[0] = (byte) (0xff & i);  
        abyte0[1] = (byte) ((0xff00 & i) >> 8);  
        abyte0[2] = (byte) ((0xff0000 & i) >> 16);  
        abyte0[3] = (byte) ((0xff000000 & i) >> 24);  
        return abyte0;  
    }  
      
}  
安卓USB通讯_手机端util_FileHelper android, usb
package com.xinxin.cigm.forms.com.otheri.util;  
  
import java.io.BufferedInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
import com.xinxin.cigm.forms.androidService;
  
import android.util.Log;  
  
public class FileHelper {  
    // private static String FILEPATH = "/data/local/tmp";   
  
    private static String FILEPATH = "/sdcard";  
  
    // private static String FILEPATH = "/tmp";   
  
    public static File newFile(String fileName) {  
        File file = null;  
        try {  
            file = new File(FILEPATH, fileName);  
            file.delete();  
            file.createNewFile();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block   
            e.printStackTrace();  
        }  
        return file;  
    }  
  
    public static void writeFile(File file, byte[] data, int offset, int count)  
            throws IOException {  
  
        FileOutputStream fos = new FileOutputStream(file, true);  
        fos.write(data, offset, count);  
        fos.flush();  
        fos.close();  
    }  
  
    public static byte[] readFile(String fileName) throws IOException {  
        File file = new File(FILEPATH, fileName);  
        file.createNewFile();  
        FileInputStream fis = new FileInputStream(file);  
        BufferedInputStream bis = new BufferedInputStream(fis);  
        int leng = bis.available();  
        Log.v(androidService.TAG, "filesize = " + leng);  
        byte[] b = new byte[leng];  
        bis.read(b, 0, leng);  
        // Input in = new Input(fis);   
        // byte[] ret = in.readAll();   
        // in.close();   
        bis.close();  
        return b;  
  
    }  
}
安卓USB通讯_手机端service_ThreadSocket android, usb
package com.xinxin.cigm.forms.com.otheri.service;  
  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;   
import java.io.File;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.Socket;  
  
import android.content.Context;  
import android.util.Log;  
  
import com.xinxin.cigm.forms.androidService;
import com.xinxin.cigm.forms.com.otheri.util.FileHelper;
import com.xinxin.cigm.forms.com.otheri.util.MyUtil;
  
/** 
 * 功能:用于socket的交互 
 *  
 * @author wufenglong 
 *  
 */  
public class ThreadReadWriterIOSocket implements Runnable {  
    private Socket client;  
    private Context context;  
  
    public ThreadReadWriterIOSocket(Context context, Socket client) {  
  
        this.client = client;  
        this.context = context;  
    }  
  
    @Override  
    public void run() {  
        Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"  
                + "a client has connected to server!");  
        BufferedOutputStream out;  
        BufferedInputStream in;  
        try {  
            /* PC端发来的数据msg */  
            String currCMD = "";  
            out = new BufferedOutputStream(client.getOutputStream());  
            in = new BufferedInputStream(client.getInputStream());  
            // testSocket();// 测试socket方法   
            androidService.ioThreadFlag = true;  
            while (androidService.ioThreadFlag) {  
                try {  
                    if (!client.isConnected()) {  
                        break;  
                    }  
  
                    /* 接收PC发来的数据 */  
                    Log.v(androidService.TAG, Thread.currentThread().getName()  
                            + "---->" + "will read......");  
                    /* 读操作命令 */  
                    currCMD = readCMDFromSocket(in);  
                    Log.v(androidService.TAG, Thread.currentThread().getName()  
                            + "---->" + "**currCMD ==== " + currCMD);  
  
                    /* 根据命令分别处理数据 */  
                    if (currCMD.equals("1")) {  
                        out.write("OK".getBytes());  
                        out.flush(); 
                    } else if (currCMD.equals("2")) {  
                        out.write("OK".getBytes());  
                        out.flush();  
                    } else if (currCMD.equals("3")) {  
                        out.write("OK".getBytes());  
                        out.flush();  
                    } else if (currCMD.equals("4")) {  
                        /* 准备接收文件数据 */  
                        try {  
                            out.write("service receive OK".getBytes());  
                            out.flush();  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
  
                        /* 接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据 */  
                        byte[] filelength = new byte[4];  
                        byte[] fileformat = new byte[4];  
                        byte[] filebytes = null;  
  
                        /* 从socket流中读取完整文件数据 */  
                        filebytes = receiveFileFromSocket(in, out, filelength,  
                                fileformat);  
  
                        // Log.v(Service139.TAG, "receive data =" + new   
                        // String(filebytes));   
                        try {  
                            /* 生成文件 */  
                            File file = FileHelper.newFile("R0013340.JPG");  
                            FileHelper.writeFile(file, filebytes, 0,  
                                    filebytes.length);  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
                    } else if (currCMD.equals("exit")) {  
  
                    }  
                } catch (Exception e) {  
                    // try {   
                    // out.write("error".getBytes("utf-8"));   
                    // out.flush();   
                    // } catch (IOException e1) {   
                    // e1.printStackTrace();   
                    // }   
                    Log.e(androidService.TAG, Thread.currentThread().getName()  
                            + "---->" + "read write error111111");  
                }  
            }  
            out.close();  
            in.close();  
        } catch (Exception e) {  
            Log.e(androidService.TAG, Thread.currentThread().getName()  
                    + "---->" + "read write error222222");  
            e.printStackTrace();  
        } finally {  
            try {  
                if (client != null) {  
                    Log.v(androidService.TAG, Thread.currentThread().getName()  
                            + "---->" + "client.close()");  
                    client.close();  
                }  
            } catch (IOException e) {  
                Log.e(androidService.TAG, Thread.currentThread().getName()  
                        + "---->" + "read write error333333");  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * 功能:从socket流中读取完整文件数据 
     *  
     * InputStream in:socket输入流 
     *  
     * byte[] filelength: 流的前4个字节存储要转送的文件的字节数 
     *  
     * byte[] fileformat:流的前5-8字节存储要转送的文件的格式(如.apk) 
     *  
     * */  
    public static byte[] receiveFileFromSocket(InputStream in,  
            OutputStream out, byte[] filelength, byte[] fileformat) {  
        byte[] filebytes = null;// 文件数据   
        try {  
            in.read(filelength);// 读文件长度   
            int filelen = MyUtil.bytesToInt(filelength);// 文件长度从4字节byte[]转成Int   
            String strtmp = "read file length ok:" + filelen;  
            out.write(strtmp.getBytes("utf-8"));  
            out.flush();  
  
            filebytes = new byte[filelen];  
            int pos = 0;  
            int rcvLen = 0;  
            while ((rcvLen = in.read(filebytes, pos, filelen - pos)) > 0) {  
                pos += rcvLen;  
            }  
            Log.v(androidService.TAG, Thread.currentThread().getName()  
                    + "---->" + "read file OK:file size=" + filebytes.length);  
            out.write("read file ok".getBytes("utf-8"));  
            out.flush();  
        } catch (Exception e) {  
            Log.v(androidService.TAG, Thread.currentThread().getName()  
                    + "---->" + "receiveFileFromSocket error");  
            e.printStackTrace();  
        }  
        return filebytes;  
    }  
  
    /* 读取命令 */  
    public static String readCMDFromSocket(InputStream in) {  
        int MAX_BUFFER_BYTES = 2048;  
        String msg = "";  
        byte[] tempbuffer = new byte[MAX_BUFFER_BYTES];  
        try {  
            int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);  
            msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");  
            tempbuffer = null;  
        } catch (Exception e) {  
            Log.v(androidService.TAG, Thread.currentThread().getName()  
                    + "---->" + "readFromSocket error");  
            e.printStackTrace();  
        }  
        // Log.v(Service139.TAG, "msg=" + msg);   
        return msg;  
    }  
}  
安卓USB通讯_手机端service_Receiver android, usb
package com.xinxin.cigm.forms.com.otheri.service;  
  
import com.xinxin.cigm.forms.androidService;

import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.util.Log;  
  
public class ServiceBroadcastReceiver extends BroadcastReceiver {  
    private static String START_ACTION = "NotifyServiceStart";  
    private static String STOP_ACTION = "NotifyServiceStop";  
  
    @Override  
    public void onReceive(Context context, Intent intent) {  
        Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"  
                + "ServiceBroadcastReceiver onReceive");  
  
        String action = intent.getAction();  
        if (START_ACTION.equalsIgnoreCase(action)) {  
            context.startService(new Intent(context, androidService.class));  
  
            Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"  
                    + "ServiceBroadcastReceiver onReceive start end");  
        } else if (STOP_ACTION.equalsIgnoreCase(action)) {  
            context.stopService(new Intent(context, androidService.class));  
            Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"  
                    + "ServiceBroadcastReceiver onReceive stop end");  
        }  
    }  
  
}
Listview按钮失效 android android中ListView点击和里边按钮或ImageView点击不能同时生效问题解决
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FriendListTwitter extends Activity {
	private List<Map<String, Object>> mListItem;
	private ListView mListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.apl_mb_c1_friend_001_01);

		mListView = (ListView) findViewById(R.id.friends);
		mListItem = getData();
		MyAdapter adapter = new MyAdapter(this);
		mListView.setAdapter(adapter);
		// 添加点击
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				startActivity(new Intent(FriendListTwitter.this,
						FriendDetail.class));
			}
		});
	}

	private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 10; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			String url = "http://10.167.12.184:8080/examples/images/1.png";
			Bitmap bitmap = getImageByURL(url);

			map.put("avatar", bitmap);// 图像资源的ID
			map.put("username", "@username " + i);
			map.put("location", "SuZhou JiangSu China");
			map.put("add", R.drawable.btn_check_on);
			list.add(map);
		}
		return list;
	}

	/**
	 * listview中点击按键弹出对话框
	 */
	public void showInfo() {
		Toast.makeText(this, "add user", Toast.LENGTH_SHORT).show();
	}

	public Bitmap getImageByURL(String url) {
		try {
			URL imgURL = new URL(url);
			URLConnection conn = imgURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			if (bm == null) {
				Log.e("MO", "httperror");
			}
			return bm;
		} catch (Exception e) {
			return null;
		}
	}

	public final class ViewHolder {
		public ImageView avatar;
		public TextView username;
		public TextView location;
		public ImageView add;
	}

	public class MyAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mListItem.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(
						R.layout.apl_mb_c1_friend_001_03, null);
				holder.avatar = (ImageView) convertView
						.findViewById(R.id.ItemImage);
				holder.username = (TextView) convertView
						.findViewById(R.id.ItemTitle1);
				holder.location = (TextView) convertView
						.findViewById(R.id.ItemTitle2);
				holder.add = (ImageView) convertView.findViewById(R.id.add);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.avatar.setImageBitmap((Bitmap) mListItem.get(position).get(
					"avatar"));
			Log.e("txl01", mListItem.get(position).get("avatar").toString());
			holder.username.setText((String) mListItem.get(position).get(
					"username"));
			holder.location.setText((String) mListItem.get(position).get(
					"location"));
			holder.add.setBackgroundResource((Integer) mListItem.get(position)
					.get("add"));
			holder.add.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					showInfo();
				}
			});
			return convertView;
		}
	}
}
上中下,中间可横滑动layout android
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="wrap_content">
	<TextView android:id="@+id/activitybase_contenttext"
		android:layout_width="fill_parent" android:layout_height="fill_parent"
		android:background="@drawable/bghead1px" android:textColor="#F8F7F5"
		android:gravity="center_vertical" />
		<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
		 android:background="@drawable/examebigbg1px" android:layout_weight="1">
	<HorizontalScrollView android:id="@+id/scrollid" android:layout_weight="1" android:layout_width="fill_parent" android:layout_height="fill_parent">
		<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content">
		  <FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> 
		 	<include layout="@layout/examslipping00"/>
		  </FrameLayout>
		   <FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> 
		 	<include layout="@layout/examslipping01"/>
		  </FrameLayout>
		<FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> 
		 	<include layout="@layout/examslipping02"/>
		  </FrameLayout>
	</LinearLayout>
	</HorizontalScrollView>
		</LinearLayout>
	<LinearLayout android:id="@+id/activitybase_foot"
		android:orientation="horizontal" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:gravity="center|center_vertical"
		android:background="@drawable/bgfoot1px">
		<Button android:id="@+id/marebutton" android:background="@drawable/buttonfoot2"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"></Button>
	</LinearLayout>
</LinearLayout>
android获取屏幕大小 android
private void init(){
		DisplayMetrics  dm = new DisplayMetrics(); 
		getWindowManager().getDefaultDisplay().getMetrics(dm); 
		       
		//获得手机的宽带和高度像素单位为px 
		int  view_w = dm.widthPixels; 
		int   view_h = dm.heightPixels; 
	}
json反射通用 json
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

public final class Json {
	
	private Json() {
		super();
	}
	
	public static Json getJson(){
		return new Json();
	}
	
	/**
	 * 生成JSON
	 * 
	 * @param obj
	 * @param map
	 * @return
	 */
	public static JSONObject toJsonObject(Object target, Map<String, String> map) throws Exception {
		if (map == null || map.size() == 0) {
			return null;
		}
		JSONObject object = new JSONObject();
		for (Iterator<Entry<String, String>> iterable = map.entrySet()
				.iterator(); iterable.hasNext();) {
			Entry<String, String> entry = iterable.next();
			Object value = getValue(target, entry.getValue());
			object.put(entry.getKey(), value);
		}
		return object;
	}
	
	/**
	 * 生成JSONARRAY
	 * @param targets
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static JSONArray toJsonArray(Object[] targets, Map<String, String> map) throws Exception {
		if (map == null || map.size() == 0) {
			return null;
		}
		JSONArray array = new JSONArray();
		for (Object target : targets) {
			array.put(toJsonObject(target, map));
		}
		return array;
	}
	
	/**
	 * 生成JSON
	 * 
	 * @param obj
	 * @param data
	 * @return
	 */
	public static JSONObject toJsonObject(Object target, String[] ... data) throws Exception {
		if (data == null || data.length == 0) {
			return null;
		}
		JSONObject object = new JSONObject();
		for (String[] strs : data) {
			Object value = getValue(target, strs[1]);
			object.put(strs[0], value);
		}
		return object;
	}
	
	/**
	 * 生成JSONARRAY
	 * @param targets
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static JSONArray toJsonArray(Object[] targets, String[] ... data) throws Exception {
		if (data == null || data.length == 0) {
			return null;
		}
		JSONArray array = new JSONArray();
		for (Object target : targets) {
			array.put(toJsonObject(target, data));
		}
		return array;
	}
	
	/**
	 * 使用反射执行Get方法
	 * @param target
	 * @param attribute
	 * @return
	 * @throws Exception
	 */
	private static Object getValue(Object target, String attribute) throws Exception {
		if(attribute.indexOf(".") == -1){
			Method method = target.getClass().getMethod(
					"get"
							+ attribute
									.replaceFirst(attribute.charAt(0) + "",
											Character.toUpperCase(attribute
													.charAt(0))
													+ ""));
			return method.invoke(target);
		}
		else{
			String[] attrs = attribute.split("[.]");
			for (String attr : attrs) {
				Object value = getValue(target, attr);
				target = value;
			}
			return target;
		}
	}
}
hibernate_sql_DaoServiceImple hiberante, sql
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

@SuppressWarnings("unchecked")
public class DaoServiceImple implements DaoService{
	protected Log log = LogFactory.getLog(getClass());
	protected SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}



	@SuppressWarnings("deprecation")
	public void executeSql(String _sql) {
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        Statement stmt = null;
        try {
            if(log.isDebugEnabled()){
                log.debug("Try to execute SQL:" + _sql);
            }
            Connection conn = sess.connection();
            stmt = conn.createStatement();
            stmt.execute(_sql);
            sess.flush();
            if(log.isDebugEnabled()){
                log.debug("SQL execute finished.");
            }
        } catch (SQLException e) {
            log.error("SQL Exception in executeSQL method", e);
            throw new RuntimeException("SQL query error");
        } catch (HibernateException e) {
            log.error("Hibernate Exception in executeSQL method", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        } finally {
            try {
                if(stmt != null)
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    
	@SuppressWarnings("deprecation")
	public Collection findAllBySql(String sql, String alias) {
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        Statement stmt = null;
        ResultSet rs = null;
        Collection result = new ArrayList();
        try {
            if(log.isDebugEnabled()){
                log.debug("Try to execute SQL:" + sql);
                log.debug("The Data want to fetch is :" + alias);
            }
            Connection conn = sess.connection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
                Object obj = rs.getObject(alias);
                result.add(obj);
                if(log.isDebugEnabled()){
                    log.debug("Search Result Object:" + "[" + obj.getClass().getName() + "]" + obj);
                }
            }
            if(log.isDebugEnabled()){
                log.debug("SQL execute finished.");
            }
        } catch (SQLException e) {
            log.error("SQL Exception in executeSQL method", e);
            throw new RuntimeException("SQL query error");
        } catch (HibernateException e) {
            log.error("Hibernate Exception in executeSQL method", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        } finally {
            try {
                if(stmt != null)
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @SuppressWarnings("deprecation")
	public Collection findAllBySql(String sql, String[] alias) {
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        Statement stmt = null;
        ResultSet rs = null;
        Collection result = new ArrayList();
        try {
            if(log.isDebugEnabled()){
                log.debug("Try to execute SQL:" + sql);
                String arrAlias = "";
                for(int i=0; i< alias.length; i++){
                    arrAlias += ("," + alias[i]);
                }
                log.debug("The Data want to fetch is :" + arrAlias.substring(1));
            }
            Connection conn = sess.connection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);

            while (rs.next()) {
                int i = 0;
                Map map = new HashMap();
                while (i < alias.length) {
                    String key = alias[i++];
                    map.put(key, rs.getObject(key));
                }
                result.add(map);
                if(log.isDebugEnabled()){
                    log.debug("Search Result Object:" + map);
                }
            }
            if(log.isDebugEnabled()){
                log.debug("SQL execute finished.");
            }
        } catch (SQLException e) {
            log.error("SQL Exception in executeSQL method", e);
            throw new RuntimeException("SQL query error");
        } catch (HibernateException e) {
            log.error("Hibernate Exception in executeSQL method", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        } finally {
            try {
                if(rs != null)
                    rs.close();
                if(stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @SuppressWarnings("deprecation")
	public Collection findAllBySql(String sql, List conditions,String[] alias) {
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        PreparedStatement stmt = null;
        ResultSet rs = null;
        Collection result = new ArrayList();
        try {
            if(log.isDebugEnabled()){
                log.debug("Try to execute SQL:" + sql);
                String arrAlias = "";
                for(int i=0; i< alias.length; i++){
                    arrAlias += ("," + alias[i]);
                }
                log.debug("The Data want to fetch is :" + arrAlias.substring(1));
            }
            Connection conn = sess.connection();
            stmt = conn.prepareStatement(sql);
            for(int i=0;i < conditions.size(); i++)
            	stmt.setObject(i+1,conditions.get(i));
            rs = stmt.executeQuery();

            while (rs.next()) {
            	int i = 0;
                Map map = new HashMap();
                while (i < alias.length) {
                    String key = alias[i++];
                    map.put(key, rs.getObject(key));
                }
                result.add(map);
                if(log.isDebugEnabled()){
                    log.debug("Search Result Object:" + map);
                }
            }
            if(log.isDebugEnabled()){
                log.debug("SQL execute finished.");
            }
        } catch (SQLException e) {
            log.error("SQL Exception in executeSQL method", e);
            throw new RuntimeException("SQL query error");
        } catch (HibernateException e) {
            log.error("Hibernate Exception in executeSQL method", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        } finally {
            try {
                if(rs != null)
                    rs.close();
                if(stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public Object findOneBySql(String sql, String alias){
    	Map result = findOneBySql(sql, new String[]{alias});
    	if(result == null)
    		return null;
    	else
    		return result.get(alias);
    }

    @SuppressWarnings("deprecation")
	public Map findOneBySql(String sql, String[] alias) {
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        Statement stmt = null;
        ResultSet rs = null;
        Map map = new HashMap();
        try {
            if(log.isDebugEnabled()){
                log.debug("Try to execute SQL:" + sql);
                String arrAlias = "";
                for(int i=0; i< alias.length; i++){
                    arrAlias += ("," + alias[i]);
                }
                log.debug("The Data want to fetch is :" + arrAlias.substring(1));
            }
            Connection conn = sess.connection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            if (rs.next()) {
                int i = 0;
                while (i < alias.length) {
                    String key = alias[i++];
                    map.put(key, rs.getObject(key));
                }
                if(log.isDebugEnabled()){
                    log.debug("Search Result Object:" + map);
                }
            }
            if(log.isDebugEnabled()){
                log.debug("SQL execute finished.");
            }
        } catch (SQLException e) {
            log.error("SQL Exception in executeSQL method", e);
            throw new RuntimeException("SQL query error");
        } catch (HibernateException e) {
            log.error("Hibernate Exception in executeSQL method", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        } finally {
            try {
                if(rs != null)
                    rs.close();
                if(stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return map;
    }


    @SuppressWarnings("deprecation")
	public void executeSP(String sql) {
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        CallableStatement cstat = null;
        try {
            if(log.isDebugEnabled()){
                log.debug("Try to execute SP:" + sql);
            }
            Connection conn = sess.connection();
            cstat = conn.prepareCall(sql);
            cstat.execute();
            if(log.isDebugEnabled()){
                log.debug("SP execute finished.");
            }
        } catch (SQLException e) {
            log.error("SQL Exception in executeSQL method", e);
            throw new RuntimeException("SQL query error");
        } catch (HibernateException e) {
            log.error("Hibernate Exception in executeSQL method", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        } finally {
            try {
                if (cstat != null) {
                    cstat.close();
                    cstat = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public Object findByPrimaryKey(Class clazz, Serializable pk) throws Exception{
    	Object bm = null;
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        if (log.isDebugEnabled()) {
            log.debug("getModelClass(),pk is:" + clazz.getName() + ":" + pk);
        }
        try {
            bm = (Object) sess.load(clazz, pk);
            Hibernate.initialize(bm);
        } catch (HibernateException e) {
            throw new Exception("Fail to find persistent object with id:" + pk);
        }
        return bm;
    }

    public Object getByPrimaryKey(Class clazz, Serializable pk){
    	Object bm = null;
        Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
        if (log.isDebugEnabled()) {
            log.debug("getModelClass(),pk is:" + clazz.getName() + ":" + pk);
        }
        bm = (Object) sess.get(clazz, pk);
        Hibernate.initialize(bm);
        return bm;
    }

    public boolean isExists(Class clazz, Serializable pk) {
        Object obj = getByPrimaryKey(clazz, pk);
        if(obj == null)
        	return false;
        else
        	return true;
    }

    public Object create(Object obj) throws Exception {
    	try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            sess.save(obj);
            sess.flush();
        } catch (HibernateException e) {
            log.error("Unable to persist object", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
        return obj;
    }

    public void create(Object[] objs) throws Exception {
    	try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            for (int i = 0; i < objs.length; i++) {
				sess.save(objs[i]);
			}
            sess.flush();
        } catch (HibernateException e) {
            log.error("Unable to persist object", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
	}

	public Object update(Object obj) {
        try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            sess.update(obj);
            sess.flush();
        } catch (HibernateException e) {
            log.error("update object error" + obj, e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
        return obj;
    }
    
    public void update(Collection objs) {
    	try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            for (Iterator iter = objs.iterator(); iter.hasNext();) {
            	sess.update(iter.next());
			}
            sess.flush();
        } catch (HibernateException e) {
            log.error("update objects error", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
	}
    
    
	public void update(Object[] objs) {
		try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            for (int i = 0; i < objs.length; i++) {
				sess.update(objs[i]);
			}
            sess.flush();
        } catch (HibernateException e) {
            log.error("update objects error", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
	}
	
	public Object saveOrUpdate(Object obj) {
		try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            sess.saveOrUpdate(obj);
            sess.flush();
        } catch (HibernateException e) {
            log.error("saveorupdate object error" + obj, e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
        return obj;
	}
	
	public void saveOrUpdate(Object[] objs) {
		try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            for (int i = 0; i < objs.length; i++) {
            	sess.saveOrUpdate(objs[i]);
			}
            sess.flush();
        } catch (HibernateException e) {
            log.error("saveorupdate object error", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
	}
	
	public void saveOrUpdate(Collection objs) {
		try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            for (Iterator iter = objs.iterator(); iter.hasNext();) {
				sess.saveOrUpdate(iter.next());
			}
            sess.flush();
        } catch (HibernateException e) {
            log.error("saveorupdate object error", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
	}
	
    public void remove(Object obj) throws Exception{
    	try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            sess.delete(obj);
        } catch (HibernateException e) {
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
    }

    public void removeByPk(Class clazz,Serializable pk) throws Exception{
    	this.remove(findByPrimaryKey(clazz, pk));
    }

    public  Collection findByOQL(String _oql)  {
        return findByOQL(_oql,null);
    }

    public  Collection findByOQL(String _oql, Map params)  {
        return findByOQL(_oql,params,-1,-1);
    }

    public  Collection findByOQL(String _oql, int begin, int count)  {
        return findByOQL(_oql, null, begin, count);
    }
    
    public  Collection findBySQL(String _sql, String[] alias)  {
        return findBySQL(_sql,-1,-1,alias);
    }

    public  Collection findByOQL(String _oql, Map params, int begin, int count)  {
        Collection list = null;
        try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            Query query = sess.createQuery(_oql);
            if(begin >= 0)
            	query.setFirstResult(begin);
            if(count >= 0)
            	query.setMaxResults(count);
            if(params != null && params.size() >0){
            	if(params != null && params.size() >0){
            		for(Iterator iter = params.keySet().iterator(); iter.hasNext();){
                		String key = (String)iter.next();
                		Object value = params.get(key);
                		if (value instanceof Collection) {
                			query.setParameterList(key,(Collection)value);
							
						}
                		else {
                			query.setParameter(key,value);	
                		}
                	}
                }
            }
            list = query.list();
        } catch (HibernateException e) {
            log.error("HibernateException--find all object error", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
        return list;
    }

    public  Collection findBySQL(String _sql, int begin, int count, String[] alias)  {
        Collection list = null;
        List result = new ArrayList();
        try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            Query query = sess.createSQLQuery(_sql);
            if(begin >= 0)
            	query.setFirstResult(begin);
            if(count >= 0)
            	query.setMaxResults(count);
            list = query.list();
            if (list != null && list.size() > 0 && begin >= 0 && count >= 0) {
            	Iterator it = list.iterator();
            	while (it.hasNext()) {
            		Map temp = new HashMap();
            		Object[] o = (Object[]) it.next();
            		int j = 0;
            		while (j < alias.length) {
                        String key = alias[j++];
                        temp.put(key, o[j-1]);
                    }
            		result.add(temp);
            	}
            } else result = (List) list;
        } catch (HibernateException e) {
            log.error("HibernateException--find all object error", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
        return result;
    }
    
	public Object findOneByOQL(String _oql){
    	return findOneByOQL(_oql,null);
    }

    public Object findOneByOQL(String _oql, Map params)  {
        Object obj = null;
        try {
            Session sess = SessionFactoryUtils.getSession(sessionFactory, false);
            Query query = sess.createQuery(_oql);
            if(params != null && params.size() >0){
            	if(params != null && params.size() >0){
                	for(Iterator iter = params.keySet().iterator(); iter.hasNext();){
                		String key = (String)iter.next();
                		Object value = params.get(key);
                		if (value instanceof Collection) {
                			query.setParameterList(key,(Collection)value);
							
						}
                		else {
                			query.setParameter(key,value);	
                		}
                	}
                }
            }
            Iterator it = query.iterate();
            while(it.hasNext())
            	obj = it.next();
        } catch (HibernateException e) {
            log.error("HibernateException--find all object error", e);
            throw SessionFactoryUtils.convertHibernateAccessException(e);
        }
        return obj;
    }

	public Blob createBlod(InputStream is) throws IOException {
		
		return Hibernate.createBlob(is);
	}
}
hibernate_sql_DaoService sql, hiberante
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.SessionFactory;

@SuppressWarnings("unchecked")
public interface DaoService {

	SessionFactory getSessionFactory();

	void setSessionFactory(SessionFactory sessionFactory);

	void executeSql(String _sql);

	
	Collection findAllBySql(String sql, String alias);

	Collection findAllBySql(String sql, String[] alias);

	Collection findAllBySql(String sql, List conditions, String[] alias);

	Object findOneBySql(String sql, String alias);

	Map findOneBySql(String sql, String[] alias);

	void executeSP(String sql);

	Object findByPrimaryKey(Class clazz, Serializable pk) throws Exception;

	Object getByPrimaryKey(Class clazz, Serializable pk);

	boolean isExists(Class clazz, Serializable pk);

	Object create(Object obj) throws Exception;
	
	void create(Object[] objs) throws Exception;

	Object update(Object obj);
	
	void update(Collection objs);
	
	void update(Object[] objs);
	
	Object saveOrUpdate(Object obj);
	
	void saveOrUpdate(Object[] objs);
	
	void saveOrUpdate(Collection objs);

	void remove(Object obj) throws Exception;

	void removeByPk(Class clazz, Serializable pk) throws Exception;

	Collection findByOQL(String _oql);

	Collection findByOQL(String _oql, Map params);

	Collection findByOQL(String _oql, int begin, int count);

	Collection findByOQL(String _oql, Map params, int begin, int count);

	Object findOneByOQL(String _oql);

	Object findOneByOQL(String _oql, Map params);
	
	public Blob createBlod(InputStream is) throws IOException;
	
	public  Collection findBySQL(String _sql, String[] alias);
	
	public  Collection findBySQL(String _sql, int begin, int count, String[] alias) ;

}
java乱码过滤器(servlet) Java解决乱码过滤器
package com.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 字符转换,使用utf-8格式的模板,模板中有非英文字符,请使用字符过虑功能
 * 需要在Web.xml文件中设置,设置形式如下:
 * <filter>
 * <filter-name>CharsetFilter</filter-name>
 * <filter-class>com.web.filter.CharsetFilter</filter-class>
 * <init-param>
 * <param-name>encoding</param-name>
 * <param-value>utf-8</param-value>
 * </init-param>
 * </filter>
 * <filter-mapping>
 * <filter-name>CharsetFilter</filter-name>
 * <url-pattern>*.do</url-pattern>
 * </filter-mapping>
 * <filter-mapping>
 * <filter-name>CharsetFilter</filter-name>
 * <url-pattern>*.jsp</url-pattern>
 * </filter-mapping>	
 * @author ran
 */

public class CharsetFilter implements Filter {
	
	protected String encoding = null;
	
	protected FilterConfig fc = null;

	public void destroy() {

		this.fc = null;
		this.encoding = null;

	}

	public void doFilter(ServletRequest request, ServletResponse repsonse,
			FilterChain chan) throws IOException, ServletException {
		
		request.setCharacterEncoding(encoding);
		repsonse.setCharacterEncoding(encoding);
		
		chan.doFilter(request, repsonse);

	}

	public void init(FilterConfig filterConfig) throws ServletException {
		
		this.fc = filterConfig;
		this.encoding = fc.getInitParameter("encoding");

	}

}
Global site tag (gtag.js) - Google Analytics