1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package cn.flightfeather.thirdappmodule.util.file
 
import android.content.Context
import android.database.Cursor
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import cn.flightfeather.thirdappmodule.bean.entity.Mediafile
import java.io.*
 
object FileUtil {
 
    val ROOT_PATH = Environment.getExternalStorageDirectory().path + File.separator + "FlightFeather" + File.separator + "File" + File.separator
 
    //复制文件
    @JvmStatic
    @Throws(IOException::class)
    fun copyFile(oldfile: File?, newfile: File?) {
        val ins = FileInputStream(oldfile)
        val out = FileOutputStream(newfile)
        //自定义缓冲对象
        val b = ByteArray(1024)
        var n = 0
        while (ins.read(b).also { n = it } != -1) {
            out.write(b, 0, b.size)
        }
        ins.close()
        out.close()
        println("copy success")
    }
 
    /**
     * 根据路径获取本机的图片
     * @param mediafile
     * @return
     */
    @JvmStatic
    fun getFileFromMediaFile(mediafile: Mediafile): File {
        return File(Environment.getExternalStorageDirectory(), mediafile.path + mediafile.description)
    }
 
    //将文件流写入磁盘
    fun writeToDisk(input: InputStream?, outputPath: String): Boolean {
        try {
            var osFile = File(outputPath)
            if (osFile.exists()) {
                osFile.delete()
                osFile = File(outputPath)
            } else if (!osFile.parentFile.exists()) {
                osFile.parentFile.mkdirs()
            }
            val fos = FileOutputStream(osFile)
            val bis = BufferedInputStream(input)
            val buffer = ByteArray(1024)
            var len: Int
            while (bis.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            bis.close()
            input?.close()
            return true
        } catch (e: IOException) {
            e.printStackTrace()
            return false
        }
    }
 
    //将图片插入到系统图库
    fun sendMediaScanBroadcast(context: Context, file: File): String? {
        try {
            val url = MediaStore.Images.Media.insertImage(context.contentResolver, file.absolutePath, file.name, null)
            val paths = arrayOf(file.absolutePath)
            MediaScannerConnection.scanFile(context, paths, null, null)
            //            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//            Uri uri = Uri.fromFile(file);
//            intent.setData(uri);
//            context.sendBroadcast(intent);
            return url
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        return null
    }
 
    fun getRealPathFromUri(context: Context, contentUri: Uri?): String {
        var cursor: Cursor? = null
        try {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                String id = contentUri.getLastPathSegment().split(":")[1];
//                final String[] imageColumns = {MediaStore.Images.Media.DATA };
//                final String imageOrderBy = null;
//                Cursor imageCursor = context.getContentResolver().query(contentUri, imageColumns,
//                        MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
//                if (imageCursor.moveToFirst()) {
//                    return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
//                }else{
//                    return null;
//                }
//            } else {
            val proj = arrayOf(MediaStore.Images.Media.DATA)
            cursor = context.contentResolver.query(contentUri, proj, null, null, null)
            val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            cursor.moveToFirst()
            return cursor.getString(column_index)
            //            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
        }
        return ""
    }
 
    /**
     * 获取文件扩展名
     */
    fun getExtensionName(filename: String?): String {
        if (!filename.isNullOrEmpty()) {
            val dot = filename.lastIndexOf('.')
            if (dot > -1 && dot < filename.length - 1) {
                return filename.substring(dot + 1)
            }
        }
        return ""
    }
 
    fun getUri(context: Context?, path: String?): Uri? {
        return getUri(context, File(path))
    }
 
    fun getUri(context: Context?, file: File): Uri? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            context?.let {
                FileProvider.getUriForFile(it, "cn.flightfeather.thirdapp.fileProvider", file)
            }
        } else {
            Uri.fromFile(file)
        }
    }
}