我在网上尝试过很多例子 但找不到任何有效的例子。
因此,请提供一个如何从文件中读取输入的工作示例 使用ANTLRInputStream
这样我就可以轻松理解。
提前致谢。
答案 0 :(得分:4)
它确实没有比将标准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插件。
答案 1 :(得分:1)
从Antlr 4.7你可以使用CharStreams:
YourLexer lexer = new YourLexer(CharStreams.fromFileName("path/to/file.lang"));
此外,从版本4.7开始,不推荐使用ANTLRFileStream。