简体   繁体   English

如何在java中从文件中获取类似EOF符号的smth

[英]How to get an smth like EOF symbol from file in java

Good day, everyone. 今天是个好日子。

I'm using sableCC , and it takes as input a Reader object. 我正在使用sableCC ,它将Reader对象作为输入。 For example this code works correctly: 例如,此代码正常工作:

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

Because StringReader returns -1 after the string is over: 因为StringReader在字符串结束后返回-1:

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: 但是,当我将相同的字符串写入文件“prog”,没有任何额外的行或字符,并在其上创建一个FileReader时,编译器会在不存在的第二行上中断,因为FileReader不是-1字符,而是返回换行符:

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? 从文件阅读器获取与StringReader相同的行为的最短方法是什么,或者SableCC可能允许横向?

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. 如果FileReader返回一个新的行字符那么这是因为文件中的新行字符,即使你的文本编辑器中不显示它。

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. 我认为例如emacs和gedit都这样做。 Try a different editor. 尝试不同的编辑器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM