我使用下面的代码来计算文件中的行数。
long numberOfLines = Files.lines(filePath).count();
根据上面的输出,如果行数是1,那么记录delimiter
(从该行的最后一个字符中提取)应替换为 <delimiter>\n
.分隔符被替换得很好,但是当我在这个操作之后尝试删除这个文件时,它没有用。
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);
}
该文件位于文件系统中,其文件大小与删除操作之前的文件大小相同。我试图打开此文件,但它向我显示“拒绝访问”错误。
我替换了Files.lines(filePath).count();
使用自定义的 java 方法来计算使用 InputStream 的行数并在最后关闭它,并且删除操作工作正常。
这是怎么回事Files.lines(String)
应该表现吗?它似乎没有关闭它用来访问文件的对象。
最佳答案
您可以使用try-with-resources
long numberofLines = 0;
try (Stream<String> stream = Files.lines(filePath)) {
numberOfLines = stream.count();
} catch (IOException ex) {
//catch exception
}
然后您可以继续您的逻辑,但流应该已经关闭。
关于Java NIO Files count()方法统计行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51639536/