问题
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