Java NIO Files count() Method for Counting the Number of Lines

和自甴很熟 提交于 2021-02-10 20:20:51

问题


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

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

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.

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.

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


回答1:


You can use 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.



来源:https://stackoverflow.com/questions/51639536/java-nio-files-count-method-for-counting-the-number-of-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!