首页 > 解决方案 > Jflex 获取输入文件名

问题描述

在 Jflex 中,如何提取输入文件名?

显示文件名.jflex:

%%

%class DisplayFilename

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

%%

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

命令运行

jflex DisplayFilename
javac DisplayFilename.java
java DisplayFilename someinputfile.txt

所需的输出:

someinputfile.txt

标签: javacompiler-constructionfilenamesjflex

解决方案


这可以通过省略%standalonejflex 文件顶部的标记来实现。这使得 jflex 不会生成默认方法,并允许用户在代码段内main()设置自己的自定义main()方法。%{ %}

在其中main(),用户可以放置自动生成的原始代码main(),但可以更新为所需的结果。

在这种情况下:

%%

%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 */ }

推荐阅读