我在网上尝试了很多例子,但没有找到任何可行的例子。
因此,请提供一个可行的示例,演示如何使用ANTLRInputStream从文件中读取输入。
这样我就可以轻松理解了。
提前致谢。
这并不比将标准的FileInputStream传递给ANTLRInputStream更复杂。
从文档中可以看出,ANTLRInputStrean对其接受的内容非常宽容,因此如果您在传递字符串或char[]数组时遇到问题,那么我认为存在更大的问题:
ANTLRInputStream()
ANTLRInputStream(char[] data, int numberOfActualCharsInArray)
This is the preferred constructor for strings as no data is copied
ANTLRInputStream(InputStream input)
ANTLRInputStream(InputStream input, int initialSize)
ANTLRInputStream(InputStream input, int initialSize, int readChunkSize)
ANTLRInputStream(Reader r)
ANTLRInputStream(Reader r, int initialSize)
ANTLRInputStream(Reader r, int initialSize, int readChunkSize)
ANTLRInputStream(String input)
Copy data in string to a local char array
你要求例子,那这就是一个例子:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
// You're going to need to implement these based on the grammar you've created
import your.package.here.MyLangListener;
import your.package.here.MyLangTranslator;
// These are generated by ANTLR
import your.package.here.parser.LangLexer;
import your.package.here.LangParser;
public class App {
public static void main(String[] args) {
String fileName = "someInputBasedOnYourGrammarRules.lang";
File file = new File(fileName);
FileInputStream fis = null;
try {
// Open the input file stream
fis = new FileInputStream(file);
// Create a CharStream that reads from standard input
ANTLRInputStream input = new ANTLRInputStream(fis);
// Create a lexer that feeds off of input CharStream
LangLexer lexer = new LangLexer(input);
// Create a buffer of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser that feeds off the tokens buffer
LangParser parser = new LangParser(tokens);
// Begin parsing at rule prog
ParseTree tree = parser.prog();
// Close the input file
fis.close();
// Create a generic parse tree walker that can trigger callbacks
ParseTreeWalker walker = new ParseTreeWalker();
// Walk the tree created during the parse, trigger callbacks
walker.walk(new MyLangListener(), tree);
System.out.println(); // print a \n after translation
// Walk the tree again to translate to java
walker.walk(new MyLangTranslator(), tree);
// Print LISP-style tree
//System.out.println(tree.toStringTree(parser));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
另外,我建议您使用ANTLR Maven插件。
YourLexer lexer = new YourLexer(CharStreams.fromFileName("path/to/file.lang"));
另外,从版本4.7开始,ANTLRFileStream已被弃用。
: (' ' | '\t' | '\r'| '\n') /{$channel=HIDDEN;}/ ; - Avid Learner