程序员KotlinAndroid开发经验谈

Kotlin总结3

2017-09-25  本文已影响83人  世外大帝

Date

这个是日常用的比较多的类,在kotlin中用传统的方法,IDEA会提示语法警告,有更好的方法,就是下面的

To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale. US for ASCII dates.

获得本地格式化请使用getDateInstance(),getDateTimeInstance(),或者getTimeInstance(),或者使用new SimpleDateFormat(String template, Locale locale),例如Locale.US为ASCII日期。

静态常量和静态方法共存


object DateUtils {
    
    const val SFStr = "yyyyMMdd"

    fun formatDate(date: Date, pattern: String): String = SimpleDateFormat(pattern).format(date)
    }

//java
DateUtils.INSTANCE.formatDate(new Date(),DateUtils.DF_YYYYMMDDHHMMSS);
//kotlin
DateUtils.formatDate(Date(),DateUtils.DF_YYYYMMDDHHMMSS)

java的引用,看起来是个单例,但是我的习惯是像java的静态方法一样调用

//工具类方法
@JvmStatic
fun formatDate(date: Date, pattern: String): String = SimpleDateFormat(pattern).format(date)

//java调用
DateUtils.formatDate(new Date(),DateUtils.DF_YYYYMMDDHHMMSS);

Kotlin读写流操作

写文件在java中是这么操作的

    public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
        InputStream in = new ByteArrayInputStream(bytes);
        File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }
        destFile.createNewFile();
        OutputStream out = new FileOutputStream(destFile);
        byte[] cache = new byte[CACHE_SIZE];
        int nRead = 0;
        while ((nRead = in.read(cache)) != -1) {
            out.write(cache, 0, nRead);
            out.flush();
        }
        out.close();
        in.close();
    }

转成kotlin后,是不允许在while中写赋值表达式的,弄好好久,发现应该是这样的

    @Throws(Exception::class)
    fun byteArrayToFile(bytes: ByteArray, filePath: String) {
        val inStream = ByteArrayInputStream(bytes)
        val destFile = File(filePath)
        if (!destFile.parentFile.exists()) {
            destFile.parentFile.mkdirs()
        }
        destFile.createNewFile()
        val out = FileOutputStream(destFile)
        val cache = ByteArray(CACHE_SIZE)
        var nRead = inStream.read(cache)

        while (nRead != -1) {
            out.write(cache, 0, nRead)
            nRead = inStream.read(cache)
        }
        inStream.copyTo(out)
        out.close()
        inStream.close()
    }

然后Slient大神发了一个扩展方法InputStream.copyTo

于是就变成这样了

@Throws(Exception::class)
fun byteArrayToFile(bytes: ByteArray, filePath: String) {
    val inStream = ByteArrayInputStream(bytes)
    val destFile = File(filePath)
    if (!destFile.parentFile.exists())
        destFile.parentFile.mkdirs()
    destFile.createNewFile()
    val out = FileOutputStream(destFile)
    inStream.copyTo(out,MemoryUtils.KB)
    out.close()
    inStream.close()
}

卧槽,感觉好多语法糖,上次忘了一个什么方法,写了半天,也是Slient大神给了个语法糖

上一篇 下一篇

猜你喜欢

热点阅读