我在web中尝试了很多例子但找不到任何工作实例。
因此,请提供一个如何从文件中读取输入的工作示例使用ANTLRInputStream
这样我就能很容易地理解。
提前谢谢。
它实际上并不比将标准FileInputStream传递给ANTLRInputStream更复杂。
从文档中可以看出,ANTLRInputStrean在接受什么方面相当自由,所以如果您在传递String或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插件。
从Antlr 4.7可以使用CharStreams:
YourLexer lexer = new YourLexer(CharStreams.fromFileName("path/to/file.lang"));
此外,从4.7版本起,ANTLRFileStream已被弃用。