'How do I get rid of depreciated code in this class file for java antlr?

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;

import java.io.FileInputStream;
import java.io.InputStream;


public class Calc {
    public static void main(String[] args) throws Exception {
        String inputFile = null;
        if ( args.length>0 ) inputFile = args[0];
        InputStream is = System.in;
        if ( inputFile!=null ) is = new FileInputStream(inputFile);
        ANTLRInputStream input = new ANTLRInputStream(is);
        CalculatorLexer lexer = new CalculatorLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        CalculatorParser parser = new CalculatorParser(tokens);
        ParseTree tree = parser.program(); // parse

        CalcVisitor calcc = new CalcVisitor();
        calcc.visit(tree);
    }

}

As far as I know, I am pretty sure the ANTLRFileStream is what is depricated, but I have tried replacing it with CharStreams, but the code I try and run keeps resulting in an error. How can I fix this?



Solution 1:[1]

Try something like this:


public static void main(String[] args) throws Exception {

  CharStream charStream = args.length > 0 
    ? CharStreams.fromFileName(args[0]) 
    : CharStreams.fromStream(System.in);

  CalculatorLexer lexer = new CalculatorLexer(charStream);
  CommonTokenStream tokens = new CommonTokenStream(lexer);
  CalculatorParser parser = new CalculatorParser(tokens);
  ParseTree tree = parser.program(); // parse

  CalcVisitor calcc = new CalcVisitor();
  calcc.visit(tree);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1