Question

Good day, everyone.

I'm using sableCC, and it takes as input a Reader object. For example this code works correctly:

compile (new StringReader ("print 1"));

Because StringReader returns -1 after the string is over:

StringReader sr = new StringReader("print 1");
while (sr.ready())
    System.out.println (sr.read());

Gives:

112
114
105
110
116
32
49
-1
... always -1

But when i write the same string into file "prog", without any extra lines, or characters, And make a FileReader on it, the compiler breaks on an nonexistent second line, because instead of a -1 character, FileReader returns newline character:

FileReader fr = new FileReader( new File("prog"));
while (fr.ready())
    System.out.println (fr.read());

Gives:

112
114
105
110
116
32
49
10

What is the shortest way to get from a file reader the same behaviour as from StringReader, or may be SableCC allows a sideway?

Was it helpful?

Solution

If the FileReader returns a new line character then that's because there is a new line character in the file, even if your text editor doesn't show it.

Unfortunately some editors add a new empty line in text files automatically when saving. I think for example that emacs and gedit both do this. Try a different editor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top