Android上传文件到FTP
2016-06-30 10:42
489 查看
<pre name="code" class="plain"> startService(service); Intent intent = new Intent(); intent.setAction("com.tianch.ftp"); sendBroadcast(intent);调用方法
</pre><pre name="code" class="java">import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.SystemClock; import android.util.Log; import android.widget.Toast; import com.tianch.tchyichang.util.Constant; import com.tianch.tchyichang.util.FileUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; public class UploadService extends Service { /** * 文件缓存txt */ // public static final String FileUtils.cacheFileFolder = // FileUtils.FileUtils.cacheFileFolder; /** * 相片缓存 */ // public static final String cacheImageFloder = FileUtils.cacheImageFloder; public static final int HAVEDATA = 0x11; public static final int UP_SUCCESS = 0x12; private static final int FTP_ERROR = 0x13; private static final int UP_FAIL = 0x14; /** * 上个文件是否上传完成 */ private boolean finishflag = true; /** * 是否循环上传 */ boolean loopflag = true; private MyReceiver myReceiver; private static String cachefileUrl = ""; private static String cacheimageUrl = ""; String url = ""; String username = "jyz"; String port = "2121"; String password = "123456"; String remotePath = ""; private String fileName; Handler mHandler = new Handler() { private Thread thread; public void handleMessage(Message msg) { switch (msg.what) { case HAVEDATA: Log.e("service", "loopflag :" + loopflag); // 所做的操作 ArrayList<String> filePath = FileUtils.getFilePath(new File(Constant.XMLDIR), ".xml"); if (filePath.size() > 0) { cachefileUrl = filePath.get(0); fileName = FileUtils.getFileName(cachefileUrl); filePath.clear(); File check = new File(cachefileUrl); //删除无大小的文件 if (check.length() == 0) { check.delete(); loopflag = true; SystemClock.sleep(200); finishflag = true; return;//重新检测 } } mHandler.sendEmptyMessage(0x333); Log.e("service", "cachefileUrl: " + cachefileUrl); Log.e("service", "XMLDIR: " + Constant.XMLDIR); Log.e("service", "fileName: " + fileName); break; case UP_SUCCESS: // 所做的操作 File file = new File(cachefileUrl); // Log.e("service", "url: " + cachefileUrl + cacheimageUrl); if (file.exists()) { file.delete(); SystemClock.sleep(200); finishflag = true; Log.e("service", "删除file文件成功" + cachefileUrl); cachefileUrl = ""; } else { { SystemClock.sleep(200); finishflag = true; } System.out.println("你要的文件没找到哦"); } /** * 判断是否还有文件====在循环前判断,如果开始就没文件不走这里就睡while(true) */ break; case FTP_ERROR: Toast.makeText(UploadService.this, "FTP客户端出错", Toast.LENGTH_SHORT).show(); break; case UP_FAIL: Toast.makeText(UploadService.this, "上传失败", Toast.LENGTH_SHORT).show(); break; case 0x333: // String fileName ="test3.txt"; // ftpUpload(Constant.urlxml, port, username, password, Constant.remotePath, , fileName); thread = new Thread() { @Override public void run() { super.run(); ftpUpload(Constant.urlxml, port, username, password, Constant.remotePath, Constant.XMLDIR, fileName); } }; thread.start(); break; default: // 所做的操作 } } ; }; @Override public void onCreate() { IntentFilter filter = new IntentFilter(); filter.addAction("com.tianch.ftp"); myReceiver = new MyReceiver(); this.registerReceiver(myReceiver, filter); Log.e("service", "onCreate"); super.onCreate(); } @Override @Deprecated public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.e("service", "onStart"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e("service", "onStartCommand"); /** * 循环检查 */ if (FileUtils.checkNetworkCanUse(UploadService.this)) { new MyThread().start(); } return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { Log.e("service", "onBind"); return null; } @Override public void onDestroy() { Log.e("service", "onDestroy"); this.unregisterReceiver(myReceiver); super.onDestroy(); } public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { /** * have data and check */ loopflag = true; System.out.println("onReceive........................."); } } class MyThread extends Thread { @Override public void run() { while (loopflag) { // Log.e("service", "loopflag :" + loopflag); /** * 判断是否还有文件 */ try { if (FileUtils.checkFileExist(new File(Constant.XMLDIR), ".xml")) { /** * 检测到文件但还没写好,需要睡一会再上传 */ // SystemClock.sleep(1000); loopflag = true; /** * 上传缓存 */ if (finishflag) { finishflag = false; Log.e("service", "检测到离线数据 :"); Message message = new Message(); message.what = HAVEDATA; mHandler.sendMessageDelayed(message, 5000);//延迟发送。FTP可能慢 // 改变上传标记 } } else { loopflag = false; Log.e("service", "未检测到离线数据 :"); } } catch (Exception e) { } } super.run(); } } public class MyRunnable implements Runnable { public void run() { // ����Ҫʵ�ֵĴ��� } } public String ftpUpload(String url, String port, String username, String password, String remotePath, String fileNamePath, String fileName) { FTPClient ftpClient = new FTPClient(); FileInputStream fis = null; String returnMessage = "0"; try { int port1 = Integer.parseInt(port); ftpClient.connect(url, port1); Log.e("service", "port1 :" + port1); boolean loginResult = ftpClient.login(username, password); int returnCode = ftpClient.getReplyCode(); Log.e("service", "returnCode :" + returnCode); if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功 ftpClient.makeDirectory(remotePath); // 设置上传目录 ftpClient.changeWorkingDirectory(remotePath); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("UTF-8"); ftpClient.enterLocalPassiveMode(); Log.e("service", "fileNamePath + fileName :" + fileNamePath + "/" + fileName); fis = new FileInputStream(fileNamePath + "/" + fileName); ftpClient.storeFile(fileName, fis); returnMessage = "1"; //上传成功 mHandler.sendEmptyMessage(UP_SUCCESS); } else {// 如果登录失败 returnMessage = "0"; mHandler.sendEmptyMessage(UP_FAIL); } } catch (IOException e) { e.printStackTrace(); mHandler.sendEmptyMessage(FTP_ERROR); throw new RuntimeException("FTP客户端出错!", e); } finally { //IOUtils.closeQuietly(fis); try { if (fis != null) { fis.close(); } ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); } } return returnMessage; } }
import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import android.content.Context; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Environment; import android.telephony.TelephonyManager; import android.util.Base64; public class FileUtils { // 文件缓存txt public static final String cacheFileFolder = Environment .getExternalStorageDirectory().getAbsolutePath() + "/tempdata/"; // 相片缓存 public static final String cacheImageFloder = Environment .getExternalStorageDirectory().getAbsolutePath() + "/tempcardPhoto/"; public static byte[] Bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } /** * @param @param arryList * @param @param cacheFile * @param @param append 是否添加 * @param @throws IOException 设定文件 * @return void 返回类型 * @throws * @Title: writeFileForLine * @Description:存储文件 */ public static void writeFileForLine(ArrayList<String> arryList, File cacheFile, Boolean append) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(cacheFile, append))); for (String string : arryList) { bufferedWriter.write(string); // bufferedWriter.newLine(); bufferedWriter.flush(); } bufferedWriter.close(); } /** * 判断SD是否可以 * * @return */ public static boolean CheckSdcardExist() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return true; } return false; } /** * 创建根目录 * * @param path 目录路径 */ public static void createDirFile(String path) { File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } } /** * 创建文件 * * @param path 文件路径 * @return 创建的文件 */ public static File createNewFile(String path) { File file = new File(path); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { return null; } } return file; } /** * @param @param context * @param @return 设定文件 * @return String 返回类型 * @throws * @Title: get ae03 IMEI * @Description: getIMEI */ public static String getIMEI(Context context) { return ((TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId(); } /** * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> * * @param @param context * @param @return 设定文件 * @return String 返回类型 * @throws * @Title: getLocalMacAddress * @Description: 获取机器MAC地址 */ public static String getLocalMacAddress(Context context) { WifiManager wifi = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); return info.getMacAddress(); } /** * bitmap转为base64 * * @param bitmap * @return */ public static String bitmapToBase64(Bitmap bitmap) { String result = null; ByteArrayOutputStream baos = null; try { if (bitmap != null) { baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); baos.flush(); baos.close(); byte[] bitmapBytes = baos.toByteArray(); result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (baos != null) { baos.flush(); baos.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * @param @param context * @param @return 设定文件 * @return boolean 返回类型 * @throws * @Title: checkInternet * @Description: 检查网络连接 */ public static boolean checkInternet(final Context context) { try { ConnectivityManager manger = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manger.getActiveNetworkInfo(); return (info != null && info.isConnected()); } catch (Exception e) { return false; } } /** * @param @param file * @param @param suffix * @param @return 设定文件 * @return Boolean 返回类型 * @throws * @Title: checkFileExist * @Description:检查指定目录下文件后缀的文件名 */ public static Boolean checkFileExist(File file, String suffix) { Boolean fileflag = false; if (!file.exists()) { return false; } File[] listFiles = file.listFiles(); int num = listFiles.length; /** * 如果没有找到文件就递归查完 */ int length = 0; if (num > 0) { if (num > 500) { length = num / 50; } else if (num > 200) { length = num / 10; } else if (num > 100) { length = num / 5; } else if (num > 60) { length = num / 3; } else if (num > 40) { length = num / 2; } else if (num > 20) { length = num / 2; } else if (num > 0) { length = num; } for (int i = 0; i < length; i++) { File subfile = listFiles[i]; if (subfile.isFile()) { if (subfile.getName().endsWith( suffix = suffix.length() > 0 ? suffix : ".txt")) { fileflag = true; } else { // 没检测到.txt结尾的文件 fileflag = false; } } else { // 检查多级目录下的.txt结尾文件 // getFilePath(subfile, suffix); // checkFileExist(subfile, suffix); } } } return fileflag; } /** * @param @param file * @param @param suffix 要查询的文件后缀名 * @param @return 设定文件 * @return ArrayList<String> 返回类型 * @throws * @Title: getFilePath * @Description:递归读取目录文件 */ public static ArrayList<String> getFilePath(File file, String suffix) { ArrayList<String> arrayList = new ArrayList<String>(); File[] listFiles = file.listFiles(); int num = listFiles.length; int length = 0; if (num > 500) { length = num / 50; } else if (num > 200) { length = num / 10; } else if (num > 100) { length = num / 5; } else if (num > 60) { length = num / 3; } else if (num > 40) { length = num / 2; } else if (num > 20) { length = num / 2; } else if (num > 0) { length = num; } for (int i = 0; i < length; i++) { File subfile = listFiles[i]; if (subfile.isDirectory()) { getFilePath(subfile, suffix); } else { if (subfile.getName().endsWith( suffix = suffix.length() > 0 ? suffix : ".txt")) { String absolutePath = subfile.getAbsolutePath(); arrayList.add(absolutePath); } } } // for (File subfile : listFiles) { // if (subfile.isDirectory()) { // getFilePath(subfile, suffix); // } else { // if (subfile.getName().endsWith(suffix = suffix.length() > 0 ? suffix // : ".txt")) { // String absolutePath = subfile.getAbsolutePath(); // arrayList.add(absolutePath); // } // } // } return arrayList; } /** * @param @param srcFile 设定文件 * @return void 返回类型 * @throws * @Title: deleteFile * @Description:文件删除 */ public static void deleteFile(File srcFile) { // 获取指定目录下所有File数组 //File数组包括文件夹和文件 File[] fileArray = srcFile.listFiles();// 根目录用srcFile表示; // 为了确保除非是系统自带的一些文件,其他的文件都可以删除。 if (fileArray != null) { // 这样不会删除有系统文件的文件夹(目录) // 遍历File数组,获取到每一个File for (File file : fileArray) {// 增强for if (file.isDirectory()) {// 判断是否是目录 deleteFile(file); // 是目录递归返回到上面方法入口调用本身; //---里面的参数 } else { // 不是目录输出提示并删除文件; System.out.println(file.getName() + "---" + file.delete()); } } // for循环外删除的是文件 //因为有递归;删除一个最里层的文件夹里面的文件就删除自身; 最后到最外层 System.out.println(srcFile.getName() + "---" + srcFile.delete());// 某个所有子目录下的文件删除后删除空文件夹本身; } } public static boolean checkNetworkCanUse(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netinfo = connectivityManager.getActiveNetworkInfo(); if (netinfo != null && netinfo.isConnected()) { return true; } return false; } public static void saveJpeg(Bitmap bm, String cacheImageName) { // long dataTake = System.currentTimeMillis(); // String jpegName = initSavePath() + dataTake + ".jpg"; // String jpegName = cacheImageName+ ".jpg"; // File jpegFile = new File(jpegName); try { File picFile = new File(cacheImageName); if (!picFile.exists()) { picFile.createNewFile(); } FileOutputStream fout = new FileOutputStream(picFile); BufferedOutputStream bos = new BufferedOutputStream(fout); // Bitmap newBM = bm.createScaledBitmap(bm, 600, 800, false); bm.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String getSuffixName(String filename) { if (filename == null) { return ""; } int start = filename.lastIndexOf("."); if (start == -1 && start >= filename.length()) { return ""; } String suffix = filename.substring(start + 1, filename.length()); return suffix; } public static String getFileName(String fileUrl){ return fileUrl.substring(fileUrl.lastIndexOf("/")+1); } }
相关文章推荐
- Android学习笔记十三之LinearLayout布局
- Android项目重构
- android:sharedUserId
- Android之ProgressBar及其子类SeekBar和RatingBar(一)
- Android行情走势图
- android 简单登陆注册的实现
- Android 事件总线Otto使用入门一
- 使用Action、Data属性启动系统Activity
- android ant混淆时遇到的错误总结
- 单例模式的几种用法比较
- Data、Type属性与intent-filter配置
- Android在屏幕适配时出现异常java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x1
- Android之LayoutInflater的使用
- DataBinding中如何使用Listener
- Android中数据库的简单运用
- android使用google gcm接收push消息需要注意的地方
- Android Bundle类 学习总结
- 浅析Android 开源框架ImageLoader的用法
- 简单实用的Android ORM框架TigerDB
- android 中几种adapter的总结