1

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.

Dhiren Dash
  • 111
  • 1
  • 10
  • 3
    `Files.lines` do not close the stream [It is a design decision](https://stackoverflow.com/questions/34072035/why-is-files-lines-and-similar-streams-not-automatically-closed) – gtgaxiola Aug 01 '18 at 18:00
  • 2
    *Warning:* [`Files.lines()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-) reads text as UTF-8, while [`new String(byte[])`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-byte:A-) uses the platform's default charset. *Inconsistent character set*. – Andreas Aug 01 '18 at 18:06
  • @gtgaxiola did not know that this was done on purpose. Thank you for the info and link. – Dhiren Dash Aug 01 '18 at 18:14

1 Answers1

3

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.

gtgaxiola
  • 9,241
  • 5
  • 42
  • 64