需求:
1.一個android端的service后台運行的程序,作為socket的服務器端;用於接收Pc client端發來的命令,來處理數據后,把結果發給PC client
2.PC端程序,作為socket的客戶端,用於給android手機端發操作命令
難點分析:
1.手機一定要有adb模式,即插上USB線時馬上提示的對話框選adb。好多對手機的操作都可以用adb直接作。
不過,我發現LG GW880就沒有,要去下載個
2.android默認手機端的IP為“127.0.0.1”
3.要想聯通PC與android手機的sokcet,一定要用adb forward 來作下端口轉發才能連上socket.
- Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086");
- Thread.sleep(3000);
4.android端的service程序Install到手機上容易,但是還要有方法來從PC的client端來啟動手機上的service ,這個辦法可以通過PC端adb命令來發一個Broastcast ,手機端再寫個接收BroastcastReceive來接收這個Broastcast,在這個BroastcastReceive來啟動service
pc端命令:
- Runtime.getRuntime().exec(
- "adb shell am broadcast -a NotifyServiceStart");
android端的代碼:ServiceBroadcastReceiver.java
- package com.otheri.service;
- 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");
- }
- }
- }
5.由於是USB連接,所以socket就可以設計為一但連接就一直聯通,即在new socket和開完out,in流后,就用個while(true){}來循環PC端和android端的讀和寫
android的代碼:
- 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();
- }
- }
6.如果是在PC端和android端的讀寫操作來while(true){}循環,這樣socket流的結尾不好判斷,不能用“-1”來判斷,因為“-1”是只有在socket關閉時才作為判斷結尾。
7.socket在out.write(bytes);時,要是數據太大時,超過socket的緩存,socket自動分包發送,所以對方就一定要用循環來多次讀。最好的辦法就是服務器和客戶端協議好,比如發文件時,先寫過來一個要發送的文件的大小,然后再發送文件;對方用這個大小,來循環讀取數據。
android端接收數據的代碼:
- /**
- * 功能:從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 {
- 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;
- }
8.socket的最重要的機制就是讀寫采用的是阻塞的方式,如果客戶端作為命令發起者,服務器端作為接收者的話,只有當客戶端client用out.writer()寫到輸出流里后,即流中有數據service的read才會執行,不然就會一直停在read()那里等數據。
9.還要讓服務器端可以同時連接多個client,即服務器端用new thread()來作數據讀取操作。
源碼:
客戶端(pc端):
testPcClient.java
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- 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 testPcClient {
- /**
- * @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;
- }
- }
android服務器端:
主類androidService.java
- package com.otheri.service;
- import java.io.File;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- 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();
- new Thread() {
- public void run() {
- doListen();
- };
- }.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;
- }
- }
用於接收PC發來的Broastcast並啟動主類service的ServiceBroadcastReceiver.java
- package com.otheri.service;
- 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");
- }
- }
- }
用於新socket連接的讀寫線程類ThreadReadWriterIOSocket.java
- package com.otheri.service;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.ByteArrayOutputStream;
- 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.otheri.util.FileHelper;
- import com.otheri.util.MyUtil;
- /**
- * 功能:用於socket的交互
- *
- * @author wufenglong
- *
- */
- public class ThreadReadWriterIOSocket implements Runnable {
- private Socket client;
- private Context context;
- 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;
- }
- }
后面是兩個輔助類:
- package 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.otheri.service.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;
- }
- }
- package com.otheri.util;
- import java.io.InputStream;
- import android.util.Log;
- import com.otheri.service.androidService;
- 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;
- }
- }
需要的朋友們,可以回復留下郵箱,少時發送到你們的郵箱。