Antlr4.7 中的文件名 CharStreams.fromFileName()
filename in Antlr4.7 CharStreams.fromFileName()
我正在尝试读取名为 test
的文件。我的程序是AntlrTest.java
。它们位于同一目录中:/Users/MyName/Documents/
。 AntlrTest.java
中的内容如下图:
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
public class AntlrTest {
public static void main(String[] args) {
String fileName = "test";
CharStream input = CharStreams.fromFileName(fileName);
}
}
文件 test
中的内容只是简单的 UTF-8 文本 a//b
。
但是,当我尝试 javac AntlrTest.java
时,它说:
error: unreported exception IOException; must be caught or declared to be thrown
CharStream input = CharStreams.fromFileName(fileName);
^
我也尝试将文件名更改为绝对路径 /Users/MyName/Documents/test
,但得到了相同的 IOException。
有人有什么建议吗?
非常感谢!
编译器显示错误和可能的解决方案。因此,使用可用的替代方案之一:
抓住IOException
并妥善处理。
try {
CharStream input = CharStreams.fromFileName(fileName);
} catch (final IOException e) {
// Handle the exception.
// For example: log (print to standard to error) it and return.
System.err.println(e);
return;
}
声明 IOException
由 main
方法抛出。
public static void main(String[] args) throws IOException {
...
}
我正在尝试读取名为 test
的文件。我的程序是AntlrTest.java
。它们位于同一目录中:/Users/MyName/Documents/
。 AntlrTest.java
中的内容如下图:
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
public class AntlrTest {
public static void main(String[] args) {
String fileName = "test";
CharStream input = CharStreams.fromFileName(fileName);
}
}
文件 test
中的内容只是简单的 UTF-8 文本 a//b
。
但是,当我尝试 javac AntlrTest.java
时,它说:
error: unreported exception IOException; must be caught or declared to be thrown
CharStream input = CharStreams.fromFileName(fileName);
^
我也尝试将文件名更改为绝对路径 /Users/MyName/Documents/test
,但得到了相同的 IOException。
有人有什么建议吗?
非常感谢!
编译器显示错误和可能的解决方案。因此,使用可用的替代方案之一:
抓住
IOException
并妥善处理。try { CharStream input = CharStreams.fromFileName(fileName); } catch (final IOException e) { // Handle the exception. // For example: log (print to standard to error) it and return. System.err.println(e); return; }
声明
IOException
由main
方法抛出。public static void main(String[] args) throws IOException { ... }