【问题标题】:Is there a way to open and close a stream easily at kotlin? [duplicate]有没有办法在 kotlin 轻松打开和关闭流? [复制]
【发布时间】:2017-09-07 13:48:51
【问题描述】:

我在 java 要做的事:

try(InputStream inputStream = new FileInputStream("/home/user/123.txt")) {

    byte[] bytes = new byte[inputStream.available()];
    inputStream.read(bytes);
    System.out.println(new String(bytes));


} catch (IOException e) {
    e.printStackTrace();
} 

但是kotlin 不知道try-with-resources!所以我的代码是

try {
    val input = FileInputStream("/home/user/123.txt")
} finally {
    // but finally scope doesn't see the scope of try!
}

有没有简单的方法来关闭流?而且我不仅仅谈论文件。有没有办法轻松关闭任何stream

【问题讨论】:

    标签: java kotlin


    【解决方案1】:

    Closeable.use 就是你要找的东西:

    val result = FileInputStream("/home/user/123.txt").use { input ->
        //Transform input to X
    }
    

    【讨论】:

    • 它是否也刷新流?
    • 当然不是。只需检查源代码。
    【解决方案2】:
     BufferedInputStream input = null;
            try {
                input = new BufferedInputStream(new FileInputStream("/home/user/123.txt"));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (input != null) {
                    input.close();
                }
            }
    

    适用于任何输入流。这只是我使用的一个例子。

    【讨论】:

    • 这是java代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多