这篇文章主要介绍Android怎么通过TCP协议上传指定目录文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。
为了方便客户抓取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协议上传指定目录文件”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。