我在网上尝试了很多例子
但找不到任何有效的例子。
因此,请提供一个如何从文件读取输入的工作示例
使用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插件。
关于java - 如何使用ANTLRInputStream从文件读取输入?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34409396/