Date
這個(gè)是日常用的比較多的類,在kotlin中用傳統(tǒng)的方法脆霎,IDEA會(huì)提示語(yǔ)法警告总处,有更好的方法,就是下面的
- 傳統(tǒng)的方法
fun formatDate(date: Date, pattern: String): String = SimpleDateFormat(pattern).format(date)
kotlin推薦方法
fun formatDate(date: Date, dateFormat: DateFormat): String = dateFormat.format(date)
提示如下
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.
獲得本地格式化請(qǐng)使用getDateInstance()睛蛛,getDateTimeInstance()鹦马,或者getTimeInstance(),或者使用new SimpleDateFormat(String template, Locale locale)
忆肾,例如Locale.US
為ASCII日期荸频。
- 但是它只提供了常用的,這些之外的客冈,還是自定義吧
靜態(tài)常量和靜態(tài)方法共存
- 工具類
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的引用旭从,看起來(lái)是個(gè)單例,但是我的習(xí)慣是像java的靜態(tài)方法一樣調(diào)用
- class可以做到场仲,如果把工具類改成class和悦,那么靜態(tài)常量就沒(méi)法用了
- 伴生對(duì)象也可以做到,但object又不允許有伴生對(duì)象
- 所以燎窘,加個(gè)注解就搞定了
@JvmStatic
- 加了注解不影響kotlin調(diào)用摹闽,只是簡(jiǎn)化了java調(diào)用
//工具類方法
@JvmStatic
fun formatDate(date: Date, pattern: String): String = SimpleDateFormat(pattern).format(date)
//java調(diào)用
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();
}
轉(zhuǎn)成kotlin后蹄咖,是不允許在while中寫賦值表達(dá)式的褐健,弄好好久,發(fā)現(xiàn)應(yīng)該是這樣的
@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大神發(fā)了一個(gè)擴(kuò)展方法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()
}
臥槽澜汤,感覺(jué)好多語(yǔ)法糖蚜迅,上次忘了一個(gè)什么方法,寫了半天俊抵,也是Slient大神給了個(gè)語(yǔ)法糖