File 相关

This commit is contained in:
luyao 2019-08-02 16:15:51 +08:00
parent 4018ff84cb
commit 66cb112629
13 changed files with 601 additions and 47 deletions

View File

@ -7,7 +7,7 @@ import luyao.ktx.R
import luyao.util.ktx.adapter.CommonAdapter
import luyao.util.ktx.base.BaseActivity
import luyao.util.ktx.bean.ItemBean
import luyao.util.ktx.ext.itemPadding
import luyao.util.ktx.ext.view.itemPadding
/**
* Created by luyao

View File

@ -103,7 +103,7 @@ publish {
userOrg = 'luyaox' //bintray.com
groupId = 'luyao.util.ktx' //访 jcenter上此项目的路径
artifactId = 'AndroidUtilKTX' //bintray.com Package
publishVersion = '0.0.5-alpha02' //
publishVersion = '0.0.5-alpha03' //
desc = 'Android Kotlin Util Code' //
website = 'https://github.com/lulululbj/AndroidUtilCodeKTX' //
}

BIN
ktx/gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Fri Jul 26 08:57:26 CST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip

172
ktx/gradlew vendored Normal file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
ktx/gradlew.bat vendored Normal file
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

Binary file not shown.

View File

@ -1,9 +1,10 @@
package luyao.util.ktx.ext
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.ClipData
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.view.View
/**
@ -58,14 +59,19 @@ fun Context.copyToClipboard(label: String, text: String) {
clipboardManager?.primaryClip = clipData
}
fun Context.checkAccessbilityServiceEnabled(serviceName: String): Boolean =
accessibilityManager.notNull({
fun Context.checkAccessbilityServiceEnabled(serviceName: String): Boolean {
val settingValue =
Settings.Secure.getString(applicationContext.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
return settingValue.notNull({
var result = false
for (serviceInfo in accessibilityManager!!.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC)) {
if (serviceInfo.id == serviceName) {
val splitter = TextUtils.SimpleStringSplitter(':')
while (splitter.hasNext()) {
if (splitter.next().equals(serviceName, true)) {
result = true
break
}
}
result
}, { false })
}

View File

@ -1,50 +1,82 @@
package luyao.util.ktx.ext
import luyao.util.ktx.func.*
import luyao.util.ktx.util.MimeType
import java.io.File
import java.nio.charset.Charset
/**
* Created by luyao
* on 2019/7/18 9:25
*/
// long 格式化 GB MB KB
val File.canListFiles: Boolean
get() = canRead() and isDirectory
val File.totalSize: Long
get() = if (isFile) length() else getFolderSize(this)
val File.formatSize: String
get() = getFormatFileSize(totalSize)
val File.mimeType: String
get() = MimeType.getMimeType(extension, isDirectory)
fun File.listFiles(isRecursive: Boolean = false, filter: ((file: File) -> Boolean)? = null): Array<out File> {
val fileList = if (!isRecursive) listFiles() else getAllSubFile(this)
var result: Array<File> = arrayOf()
return if (filter == null) fileList
else {
for (file in fileList) {
if (filter(file)) result = result.plus(file)
}
result
}
}
fun File.writeText(append: Boolean = false, text: String, charset: Charset = Charsets.UTF_8) {
if (append) appendText(text, charset) else writeText(text, charset)
}
fun File.writeBytes(append: Boolean = false, bytes: ByteArray) {
if (append) appendBytes(bytes) else writeBytes(bytes)
}
/**
* [destFile] dest file/folder
* [overwrite] whether to override dest file/folder if exist
* [reserve] Whether to reserve source file/folder
*/
fun File.moveTo(destFile: File, overwrite: Boolean = true, reserve: Boolean = true): Boolean {
val dest = copyRecursively(destFile, overwrite)
if (!reserve) deleteRecursively()
return dest
}
/**
* [destFolder] dest folder
* [overwrite] whether to override dest file/folder if exist
* [func] progress callback (from 0 to 100)
*/
fun File.moveToWithProgress(
destFolder: File,
overwrite: Boolean = true,
reserve: Boolean = true,
func: ((file: File, i: Int) -> Unit)? = null
) {
if (isDirectory) copyFolder(this, File(destFolder, name), overwrite, func)
else copyFile(this, File(destFolder, name), overwrite, func)
if (!reserve) deleteRecursively()
}
fun File.rename(newName: String) =
rename(File("$parent${File.separator}$newName"))
fun File.rename(newFile: File) =
if (newFile.exists()) false else renameTo(newFile)
// 获取内部存储容量,可用,已用空间
// 获取 File 大小
// chmod Os.chmod() 是否可用?
// createSymlink
// isSymlink
// create
// delete deleteFile deleteFolder delete(filter)
// writeToFile(InputStream)
// writeToFile(ByteArray)
// copyFile(File,File) copyFile(String,String) /move
// copyFolder(File,File) copyFolder(String,String) /move
// close
// rename(String) rename(File)
// isFile isFolder
// create(是否保留源文件)
// listFile(filter) 是否遍历子文件夹
// getCharset
// 获取后缀名 获取文件名不含后缀
// mimeType
// parentPath
// 文件名冲突

View File

@ -113,4 +113,12 @@ fun Context.uninstallApp(packageName: String) {
}
}
fun Context.sendEmail(email: String, subject: String?, text: String?) {
Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email")).run {
subject?.let { putExtra(Intent.EXTRA_SUBJECT, subject) }
text?.let { putExtra(Intent.EXTRA_TEXT, text) }
startActivity(this)
}
}

View File

@ -1,13 +1,19 @@
package luyao.util.ktx.ext
package luyao.util.ktx.ext.view
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import luyao.util.ktx.ext.dp2px
/**
* Created by luyao
* on 2019/6/14 14:07
*/
fun RecyclerView.itemPadding(padding:Int) {
addItemDecoration(PaddingItemDecoration(padding, padding, padding, padding))
}
fun RecyclerView.itemPadding(top: Int, bottom: Int, left: Int = 0, right: Int = 0) {
addItemDecoration(PaddingItemDecoration(top, bottom, left, right))
}

View File

@ -0,0 +1,105 @@
package luyao.util.ktx.func
import luyao.util.ktx.ext.canListFiles
import java.io.*
import java.nio.ByteBuffer
import java.text.DecimalFormat
/**
* Created by luyao
* on 2019/7/23 9:29
*/
fun getFolderSize(file: File): Long {
var total = 0L
for (subFile in file.listFiles()) {
total += if (subFile.isFile) subFile.length()
else getFolderSize(subFile)
}
return total
}
fun getFormatFileSize(size: Long, unit: Int = 1000): String {
val formatter = DecimalFormat("####.00")
return when {
size < 0 -> "0 B"
size < unit -> "$size B"
size < unit * unit -> "${formatter.format(size / unit)} KB"
size < unit * unit * unit -> "${formatter.format(size / unit / unit)} MB"
else -> "${formatter.format(size / unit / unit / unit)} GB"
}
}
fun getAllSubFile(folder: File): Array<File> {
var fileList: Array<File> = arrayOf()
if (!folder.canListFiles) return fileList
for (subFile in folder.listFiles())
fileList = if (subFile.isFile) fileList.plus(subFile)
else fileList.plus(getAllSubFile(subFile))
return fileList
}
fun copyFile(sourceFile: File, destFile: File, overwrite: Boolean, func: ((file: File, i: Int) -> Unit)? = null) {
if (!sourceFile.exists()) return
if (destFile.exists()) {
val stillExists = if (!overwrite) true else !destFile.delete()
if (stillExists) {
return
}
}
if (!destFile.exists()) destFile.createNewFile()
val inputStream = FileInputStream(sourceFile)
val outputStream = FileOutputStream(destFile)
val iChannel = inputStream.channel
val oChannel = outputStream.channel
val totalSize = sourceFile.length()
val buffer = ByteBuffer.allocate(1024)
var hasRead = 0f
var progress = -1
while (true) {
buffer.clear()
val read = iChannel.read(buffer)
if (read == -1)
break
buffer.limit(buffer.position())
buffer.position(0)
oChannel.write(buffer)
hasRead += read
func?.let {
val newProgress = ((hasRead / totalSize) * 100).toInt()
if (progress != newProgress) {
progress = newProgress
it(sourceFile, progress)
}
}
}
inputStream.close()
outputStream.close()
}
fun copyFolder(sourceFolder: File, destFolder: File, overwrite: Boolean, func: ((file: File, i: Int) -> Unit)? = null) {
if (!sourceFolder.exists()) return
if (!destFolder.exists()) {
val result = destFolder.mkdirs()
if (!result) return
}
for (subFile in sourceFolder.listFiles()) {
if (subFile.isDirectory) {
copyFolder(subFile, File("${destFolder.path}${File.separator}${subFile.name}"), overwrite, func)
} else {
copyFile(subFile, File(destFolder, subFile.name), overwrite, func)
}
}
}

View File

@ -0,0 +1,135 @@
package luyao.util.ktx.util
import android.webkit.MimeTypeMap
import java.util.*
import java.util.regex.Pattern
class MimeType {
companion object {
private const val ALL_MIME_TYPES = "*/*"
private val MIME_TYPES = HashMap<String, String>(1 + (66 / 0.75).toInt())
fun getMimeType(extension: String, isDirectory: Boolean): String {
if (isDirectory) {
return ""
}
var type: String? = ALL_MIME_TYPES
// mapping extension to system mime types
if (extension.isNotEmpty()) {
val extensionLowerCase = extension.toLowerCase(Locale
.getDefault())
val mime = MimeTypeMap.getSingleton()
type = mime.getMimeTypeFromExtension(extensionLowerCase)
if (type == null) {
type = MIME_TYPES[extensionLowerCase]
}
}
if (type == null) type = ALL_MIME_TYPES
return type
}
fun mimeTypeMatch(mime: String, input: String): Boolean {
return Pattern.matches(mime.replace("*", ".*"), input)
}
/**
* Helper method for [.getMimeType]
* to calculate the last '.' extension of files
* @param path the path of file
* @return extension extracted from name in lowercase
*/
fun getExtension(path: String): String {
return if (path.contains("."))
path.substring(path.lastIndexOf(".") + 1).toLowerCase()
else
""
}
}
init {
/*
* ================= MIME TYPES ====================
*/
MIME_TYPES["asm"] = "text/x-asm"
MIME_TYPES["json"] = "application/json"
MIME_TYPES["js"] = "application/javascript"
MIME_TYPES["def"] = "text/plain"
MIME_TYPES["in"] = "text/plain"
MIME_TYPES["rc"] = "text/plain"
MIME_TYPES["list"] = "text/plain"
MIME_TYPES["log"] = "text/plain"
MIME_TYPES["pl"] = "text/plain"
MIME_TYPES["prop"] = "text/plain"
MIME_TYPES["properties"] = "text/plain"
MIME_TYPES["rc"] = "text/plain"
MIME_TYPES["ini"] = "text/plain"
MIME_TYPES["md"] = "text/markdown"
MIME_TYPES["epub"] = "application/epub+zip"
MIME_TYPES["ibooks"] = "application/x-ibooks+zip"
MIME_TYPES["ifb"] = "text/calendar"
MIME_TYPES["eml"] = "message/rfc822"
MIME_TYPES["msg"] = "application/vnd.ms-outlook"
MIME_TYPES["ace"] = "application/x-ace-compressed"
MIME_TYPES["bz"] = "application/x-bzip"
MIME_TYPES["bz2"] = "application/x-bzip2"
MIME_TYPES["cab"] = "application/vnd.ms-cab-compressed"
MIME_TYPES["gz"] = "application/x-gzip"
MIME_TYPES["lrf"] = "application/octet-stream"
MIME_TYPES["jar"] = "application/java-archive"
MIME_TYPES["xz"] = "application/x-xz"
MIME_TYPES["Z"] = "application/x-compress"
MIME_TYPES["bat"] = "application/x-msdownload"
MIME_TYPES["ksh"] = "text/plain"
MIME_TYPES["sh"] = "application/x-sh"
MIME_TYPES["db"] = "application/octet-stream"
MIME_TYPES["db3"] = "application/octet-stream"
MIME_TYPES["otf"] = "application/x-font-otf"
MIME_TYPES["ttf"] = "application/x-font-ttf"
MIME_TYPES["psf"] = "application/x-font-linux-psf"
MIME_TYPES["cgm"] = "image/cgm"
MIME_TYPES["btif"] = "image/prs.btif"
MIME_TYPES["dwg"] = "image/vnd.dwg"
MIME_TYPES["dxf"] = "image/vnd.dxf"
MIME_TYPES["fbs"] = "image/vnd.fastbidsheet"
MIME_TYPES["fpx"] = "image/vnd.fpx"
MIME_TYPES["fst"] = "image/vnd.fst"
MIME_TYPES["mdi"] = "image/vnd.ms-mdi"
MIME_TYPES["npx"] = "image/vnd.net-fpx"
MIME_TYPES["xif"] = "image/vnd.xiff"
MIME_TYPES["pct"] = "image/x-pict"
MIME_TYPES["pic"] = "image/x-pict"
MIME_TYPES["adp"] = "audio/adpcm"
MIME_TYPES["au"] = "audio/basic"
MIME_TYPES["snd"] = "audio/basic"
MIME_TYPES["m2a"] = "audio/mpeg"
MIME_TYPES["m3a"] = "audio/mpeg"
MIME_TYPES["oga"] = "audio/ogg"
MIME_TYPES["spx"] = "audio/ogg"
MIME_TYPES["aac"] = "audio/x-aac"
MIME_TYPES["mka"] = "audio/x-matroska"
MIME_TYPES["jpgv"] = "video/jpeg"
MIME_TYPES["jpgm"] = "video/jpm"
MIME_TYPES["jpm"] = "video/jpm"
MIME_TYPES["mj2"] = "video/mj2"
MIME_TYPES["mjp2"] = "video/mj2"
MIME_TYPES["mpa"] = "video/mpeg"
MIME_TYPES["ogv"] = "video/ogg"
MIME_TYPES["flv"] = "video/x-flv"
MIME_TYPES["mkv"] = "video/x-matroska"
}
}