Skip to content

Commit

Permalink
加入判断字节是否为 utf8 的方法
Browse files Browse the repository at this point in the history
  • Loading branch information
yizeliang committed Nov 25, 2022
1 parent bfbe425 commit 7675fff
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
39 changes: 39 additions & 0 deletions WIKI_ALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,45 @@ object IDCardValidator {
VinValidator.validatorVin(vin: String): Boolean
```

### 流/IO/ByteArray 辅助类

```kotlin
/**
* 写入文件,并关闭流
* 注意, 如果文件存在,会自动删除
* 如果不存在的话:会自动创建父级目录
* @param file 文件
*/
fun InputStream.writeTo(file: File)

/**
* 判断流第一个字节是否utf8
*
* 65533 = Utf8.kt: REPLACEMENT_CODE_POINT
*/
fun Buffer.startUtf8(): Boolean

/**
* 第一个字节是否utf8
*
* 65533 = Utf8.kt: REPLACEMENT_CODE_POINT
*/
fun ByteArray.startUtf8(): Boolean

/**
* 利用前 64 个字节判断是否为utf8编码
* @return true utf8
*/
fun Buffer.isUtf8(): Boolean

/**
* 利用前 64 个字节判断是否为utf8编码
* @return true utf8
*/
fun ByteArray.isUtf8(): Boolean

```

## android-context 安卓Context 工具类

### ContextHolder.kt 引入即可全局获取 Context
Expand Down
57 changes: 57 additions & 0 deletions comm/src/main/java/cn/yizems/util/ktx/comm/io/IOEx.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package cn.yizems.util.ktx.comm.io

import okio.Buffer
import okio.EOFException
import java.io.File
import java.io.InputStream

Expand All @@ -21,3 +23,58 @@ fun InputStream.writeTo(file: File) {
}
}
}

/**
* 判断流第一个字节是否utf8
*
* 65533 = Utf8.kt: REPLACEMENT_CODE_POINT
*/
fun Buffer.startUtf8(): Boolean {
return try {
readUtf8CodePoint() != 65533
} catch (e: EOFException) {
false
}
}

/**
* 第一个字节是否utf8
*
* 65533 = Utf8.kt: REPLACEMENT_CODE_POINT
*/
fun ByteArray.startUtf8(): Boolean {
return Buffer().write(this).startUtf8()
}

/**
* 利用前 64 个字节判断是否为utf8编码
* @return true utf8
*/
fun Buffer.isUtf8(): Boolean {
try {
val prefix = Buffer()
val byteCount = minOf(size, 64)
copyTo(prefix, 0, byteCount)

for (i in 0 until 16) {
if (prefix.exhausted()) {
return false
}
val codePoint = prefix.readUtf8CodePoint()
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false
}
}
return true
} catch (e: Exception) {
return false
}
}

/**
* 利用前 64 个字节判断是否为utf8编码
* @return true utf8
*/
fun ByteArray.isUtf8(): Boolean {
return Buffer().write(this).isUtf8()
}

0 comments on commit 7675fff

Please sign in to comment.