java - 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
解决方案
这可以通过省略%standalone
jflex 文件顶部的标记来实现。这使得 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 */ }
推荐阅读
- django - 使用 django 从数据库中删除/重置一个/多个(指定)模型
- enums - 如何从 Hasura 创建一个 get-graphql-schema 枚举?
- python - 为什么我在 O(n) 中得到 TLE?是因为 Python 吗?请帮助我卡住了。| 图表 | BFS | 数字文件系统 | 蟒蛇 | C++ |
- linux - 在特定 CPU 上运行进程
- c# - 构造函数未找到异常
- mamp - MAMP PRO - 糟糕,您的序列号似乎有问题
- javascript - javascript中不区分大小写的字符串比较
- laravel - Laravel如何合并2个集合
- nginx - GKE 入口传递 cookie 作为标头
- cmake - 有没有办法计算使用 Ninja/Cmake 在构建过程中发生错误的文件数?