Kotlin的特性
1.Kotlin提供了非常多,File、Stream、Reader、Writer的拓展方法
2.使用use拓展自动关闭资源
3.小文件一次性读写操作
一、首先来看看繁琐的JavaIO操作,来读取一个文件
package cn.kotliner.java.io;
import java.io.*;
/**
* Created by wangdong
* Java中的IO操作
*/
public class IO {
public static void main(String... args) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File("build.gradle")));
String line;
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、如果用Kotlin直接译一中的JavaIO代码
package cn.kotliner.kotlin.io
import java.io.*
/**
* Created by wangdong
* Kotlin直译Java中的IO操作
*/
fun main(args: Array<String>) {
val file = File("build.gradle")
val bufferedReader = BufferedReader(FileReader(file))
var line: String
while(true){
line = bufferedReader.readLine()?:break
println(line)
}
bufferedReader.close()
}
三、使用Kotlin中use方法去改写
package cn.kotliner.kotlin.io
import java.io.*
/**
* Created by wangdong
* 使用kotlin中的use的方法改写
*/
fun main(args: Array<String>) {
val file = File("build.gradle")
BufferedReader(FileReader(file)).use {
var line: String
while(true){
line = it.readLine()?:break
println(line)
}
}
}
/**
* 第十行use点进去,就可以看到use是怎么实现的
*/
/**
@InlineOnly
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}*/
四、使用kotlin中的readlin()方法改写一下
package cn.kotliner.kotlin.io
import java.io.*
/**
* Created by wangdong
* 使用readlines()方法改写
*/
fun main(args: Array<String>) {
File("build.gradle").readLines().forEach(::println)
}
/**
* Reads the file content as a list of lines.
*
* Do not use this function for huge files.
*
* @param charset character set to use. By default uses UTF-8 charset.
* @return list of file lines.
public fun File.readLines(charset: Charset = Charsets.UTF_8): List<String> {
val result = ArrayList<String>()
forEachLine(charset) { result.add(it); }
return result
}*/