1. 程式人生 > 程式設計 >Android 通過TCP協議上傳指定目錄檔案的方法

Android 通過TCP協議上傳指定目錄檔案的方法

為了方便客戶抓取Log,現通過TCP協議連線指定伺服器,傳輸指定內容,定義指定目錄,IP,PORT欄位接收引數。直接上程式碼

 public static void uploadLog(final String dirPath,final String IP,final int port ) {
 JSONArray fileList = new JSONArray();
 final JSONArray allFiles = getAllFiles(fileList,dirPath);
 if(allFiles==null)return;
 new Thread(){
  @Override
  public void run() {
  super.run();
  try {
   Socket socket=new Socket(IP,port);
   if(!socket.isConnected())return; //判斷是否建立連線
   OutputStream os = socket.getOutputStream();
   int index = dirPath.lastIndexOf("/")+1;
   os.write(dirPath.substring(index).getBytes());//TAG
   os.write("\r\n".getBytes());
 
   for (int i=0;i<allFiles.length();i++){
   try {
    JSONObject o = (JSONObject) allFiles.get(i);
    String path = o.getString("path");
    String name = o.getString("name");
    FileInputStream fis=new FileInputStream(path);
    if(fis!=null){
    InputStreamReader inputreader = new InputStreamReader(fis);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line;
    while ((line=buffreader.readLine())!=null){ //按行讀取檔案內容
     os.write(line.getBytes());
     os.write("\r\n".getBytes());//向伺服器端傳送檔案
    }
    buffreader.close();
    inputreader.close();
    }
    fis.close();
 
 
   } catch (JSONException e) {
    e.printStackTrace();
   }
   }
   //關閉客戶端輸出流,中斷上傳
   socket.shutdownOutput();
   socket.close();
 
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
 }.start();
 
 }
 
 /**
 * 獲取指定目錄內所有檔案路徑
 * @param dirPath 需要查詢的檔案目錄
 */
 public static JSONArray getAllFiles(JSONArray fileList,String dirPath) {
 File f = new File(dirPath);
 if (!f.exists()) {//判斷路徑是否存在
  return null;
 }
 File[] files = f.listFiles();
 
 if(files==null){//判斷許可權
  return null;
 }
 for (File _file : files) {//遍歷目錄
  if(_file.isFile()){
 
  String _name=_file.getName();
  String filePath = _file.getAbsolutePath();//獲取檔案路徑
  int end=_file.getName().lastIndexOf('.');
  String fileName = _file.getName().substring(0,end);//獲取檔名
  try {
   JSONObject _fInfo = new JSONObject();
   _fInfo.put("name",fileName);
   _fInfo.put("path",filePath);
   fileList.put(_fInfo);
 
 
  }catch (Exception e){
  }
  } else if(_file.isDirectory()){//查詢子目錄
  getAllFiles(fileList,_file.getAbsolutePath());
  } else{
  }
 }
 return fileList;
 }

必須宣告一下許可權:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

設計思路:

1首先通過第三方應用傳過來的Log路徑,通過遍歷該路徑,得到該目錄下的所有檔案,儲存到集合中,

2然後通過socker建立通訊,通訊建立成功後開始傳輸日誌,

3讀取指定目錄下的日誌檔案,解析內容傳輸到服務端,

4日誌按行讀取,

5內容頭部增加TAG以區分不同應用的日誌

服務端是因為有現成的軟體,所以這裡就不做解析了。

LogUtil.uploadLog("storage/emulated/0/C28Log/CarRecorderLog","10.0.16.252",8088);

Android 通過TCP協議上傳指定目錄檔案的方法

總結

到此這篇關於Android 通過TCP協議上傳指定目錄檔案的文章就介紹到這了,更多相關android 上傳指定目錄檔案內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!