Java NIO文件count()方法,用于计算行数 [英] Java NIO Files count() Method for Counting the Number of Lines

查看:133
本文介绍了Java NIO文件count()方法,用于计算行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来计算文件中的行数.

I was using the below code to calculate the number of lines in a file.

long numberOfLines = Files.lines(filePath).count();

根据上面的输出,如果行数为1,则记录 delimiter (从行的最后一个字符中提取)应替换为 ; \ n .分隔符被替换掉很好,但是当我在执行此操作后尝试删除此文件时,它不起作用.

Based on the output of the above, if the number of lines is 1, then the record delimiter (extracted from the last character of the line) should be replaced by <delimiter>\n. The delimiter got replaced fine, but when I tried to delete this file after this operation, it did not work.

if (numberOfLines == 1) {
                String rawData = (new String(Files.readAllBytes(filePath))).trim();
                String toReplace = rawData.substring(rawData.length() - 1);
                String outString = rawData.replaceAll(toReplace, toReplace + "\n");
                Files.delete(filePath);
            }

文件所在的文件系统与删除操作之前的文件大小相同.我试图打开此文件,它显示出访问被拒绝"错误.

The file lied there in the filesystem having the same filesize which it had before the delete operation. I tried to open this file and it showed me an "Access Denied" error.

我用自定义的java方法将 Files.lines(filePath).count(); 替换为使用InputStream计数行数并最终将其关闭,并且删除操作有效很好.

I replaced Files.lines(filePath).count(); with a customized java method to count the number of lines using an InputStream and closing it in the end, and the delete operation was working fine.

这是 Files.lines(String)的行为方式吗?似乎没有关闭它用来访问文件的对象.

Is this how Files.lines(String) should behave? It seems it is not closing the object which it used to access the file.

推荐答案

您可以使用 try-with-resources

long numberofLines = 0;
try (Stream<String> stream = Files.lines(filePath)) {
        numberOfLines = stream.count();
} catch (IOException ex) {
    //catch exception
}

然后,您可以继续执行逻辑操作,但是流应该已经关闭.

Then you can continue with your logic but the stream should already be closed.

这篇关于Java NIO文件count()方法,用于计算行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆