aliyun-oss-react-native

FileUtils.java 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.reactlibrary.utils;
  2. import android.content.Context;
  3. import android.net.Uri;
  4. import android.os.Environment;
  5. import android.text.TextUtils;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. public class FileUtils {
  12. /**
  13. * copy file
  14. * @param context
  15. * @param srcUri
  16. * @param dstFile
  17. */
  18. public static void copy(Context context, Uri srcUri, File dstFile) {
  19. try {
  20. InputStream is = context.getContentResolver().openInputStream(srcUri);
  21. if (is == null) return;
  22. OutputStream fos = new FileOutputStream(dstFile);
  23. int ch = 0;
  24. try {
  25. while((ch=is.read()) != -1){
  26. fos.write(ch);
  27. }
  28. } catch (IOException e1) {
  29. e1.printStackTrace();
  30. } finally{
  31. // close inputstream
  32. fos.close();
  33. is.close();
  34. }
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. /**
  40. * getFileName
  41. * @param uri
  42. * @return
  43. */
  44. public static String getFileName(Uri uri) {
  45. if (uri == null) return null;
  46. String fileName = null;
  47. String path = uri.getPath();
  48. int cut = path.lastIndexOf('/');
  49. if (cut != -1) {
  50. fileName = path.substring(cut + 1);
  51. }
  52. return fileName;
  53. }
  54. /**
  55. * getFilePathFromURI
  56. * @param context
  57. * @param contentUri
  58. * @return
  59. */
  60. public static String getFilePathFromURI(Context context, Uri contentUri) {
  61. //copy file and send new file path
  62. String fileName = getFileName(contentUri);
  63. if (!TextUtils.isEmpty(fileName)) {
  64. File copyFile = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName);
  65. FileUtils.copy(context, contentUri, copyFile);
  66. return copyFile.getAbsolutePath();
  67. }
  68. return null;
  69. }
  70. }