简体   繁体   English

Jflex 获取输入文件名

[英]Jflex get input filename

In Jflex, how does one extract the input filename?在 Jflex 中,如何提取输入文件名?

DisplayFilename.jflex:显示文件名.jflex:

%%

%class DisplayFilename

%eof{
    /* code to print the input filename goes here */
%eof}

%%

\n { /* do nothing */ }
. { /* do nothing */ }

Commands ran命令运行

jflex DisplayFilename
javac DisplayFilename.java
java DisplayFilename someinputfile.txt

desired output:所需的 output:

someinputfile.txt

This can be achieved by omitting the %standalone tag at the top of the jflex file.这可以通过省略 jflex 文件顶部的%standalone标记来实现。 This makes jflex not generate the default main() method and allows the user to set their own custom main() method inside of a %{ %} code segment.这使得 jflex 不会生成默认的main()方法,并允许用户在%{ %}代码段内设置自己的自定义main()方法。

Within this main() , the user can place the original code for the autogenerated main() , but can update to the desired outcome.在这个main()中,用户可以放置自动生成的main()的原始代码,但可以更新为所需的结果。

Within this context:在这种情况下:

%%

%class DisplayFilename

%{
  private static String inputfilename = "";
  
  private static class Yytoken {
    /* empty class to allow yylex() to compile */
  }

  public static void main(String argv[]) {
    if (argv.length == 0) {
      System.out.println("Usage : java DisplayFilename");
    }
    else {
      int firstFilePos = 0;
      String encodingName = "UTF-8";
      for (int i = firstFilePos; i < argv.length; i++) {
        inputfilename = argv[i]; // LINE OF INTEREST
        WC scanner = null;
        try {
          java.io.FileInputStream stream = new java.io.FileInputStream(argv[i]);
          java.io.Reader reader = new java.io.InputStreamReader(stream, encodingName);
          scanner = new WC(reader);
          while ( !scanner.zzAtEOF ) scanner.yylex();
        }
        catch (java.io.FileNotFoundException e) {
          System.out.println("File not found : \""+argv[i]+"\"");
        }
        catch (java.io.IOException e) {
          System.out.println("IO error scanning file \""+argv[i]+"\"");
          System.out.println(e);
        }
        catch (Exception e) {
          System.out.println("Unexpected exception:");
          e.printStackTrace();
        }
      }
    }
  }
%}


%eof{
    /* code to print the input filename goes here */
      System.out.println(inputfilename);
%eof}

%%

\n { /* do nothing */ }
. { /* do nothing */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM