2

I am reading a piece code as below:

private String loadAsString(final String path) {
    try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            Scanner scanner = new Scanner(inputStream)) {
        // '\\A' is the delimiter of .sql file?
        return scanner.useDelimiter("\\A").next();
    } catch (IOException e) {
        throw new RuntimeException("Unable to close input stream.", e);
    }
}

where path = "***.sql", which means an SQL file on my computer.

My question is why the pattern "\A" is used as the delimiter to end the reading of the SQL file? As I know, "\A" is the regex of Java for the beginning of an input but not the ending. Thanks for help.

Z.Wei
  • 3,658
  • 2
  • 17
  • 28
  • Take a look https://stackoverflow.com/questions/1497569/how-to-execute-sql-script-file-using-jdbc – AMB May 31 '17 at 14:21
  • @AMB That doesn't answer the question. – Dave Newton May 31 '17 at 14:22
  • The fact that this causes confusion is exactly why “tricks” like this should be avoided. There is no benefit to this; it only serves to make readers of the code wonder what the intent is. `"\\z"` would have worked just as well, and it would have matched the intent of the code. – VGR May 31 '17 at 15:42
  • @VGR I try with "\\z". Doesn't work. – Z.Wei May 31 '17 at 16:18
  • I think others have explained why "\\A" works. – Z.Wei May 31 '17 at 16:19

2 Answers2

3

next() will (a) skip the delimiter, and then (b) read characters until the next delimiter, or EOF, whichever comes first.

If the delimiter is \A, the start of input, then (a) above will "skip" the 0-length start-of-input-point, and then (b) read characters until the next start of input, or EOF. Since there isn't any next start of input, (b) becomes "read characters until EOF."

The scanner's tokenization essentially provides the same directions that the King does in Alice in Wonderland: "Begin at the beginning, and go on till you come to the end: then stop."

yshavit
  • 42,327
  • 7
  • 87
  • 124
1

It reads the entire content of the file as a string.

https://ratherbsailing.wordpress.com/2011/11/01/reading-a-string-from-an-inputstream-in-one-line/

Dave Newton
  • 158,873
  • 26
  • 254
  • 302