kotlin中使用AutoClosable特性进行复制文件

kotlin中使用AutoClosable特性进行复制文件

java7以后提供了try with resources与AutoClosable两个特性,使得复制文件方式简洁了些:

private void copyFile(String srcPath, String dstPath) {
    File srcFile = new File(srcPath);
    if (!srcFile.exists()) {
        return;
    }
    File dstFile = new File(dstPath);
    try (InputStream input = new FileInputStream(srcFile);
            OutputStream output = new FileOutputStream(dstFile)) {
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) {
            output.write(buf, 0, bytesRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

kotlin中提倡函数式编程,try with resources特性对它来说没有意义,因此kotlin提供了use内联函数,可以很方便的使用函数式风格来实现AutoClosable特性
kotlin中也没有了可检查异常(Checked Exception),我个人比较不赞同在编译阶段不检查异常这种做法,这样做不利于经验不足的开发者提前做好异常控制,好在kotlin1.3中加入了runCatching这个内联函数,这样就能使用函数式风格来处理异常控制

fun copyFile(srcPath: String, dstPath: String) {
    File(srcPath).runCatching {
        takeIf { it.exists() }?.inputStream()?.use { inputStream ->
            File(dstPath).outputStream().use { outputStream ->
                inputStream.copyTo(outputStream)
            }
        }
    }.onFailure { // print or throw }
}

注意:本文仅讨论kotlin与java使用IO复制文件,NIO不在讨论范围内

发布了174 篇原创文章 · 获赞 119 · 访问量 55万+

猜你喜欢

转载自blog.csdn.net/lj402159806/article/details/103100220