java - 使用不同的控制台时找不到文本文档
问题描述
我尝试使用 CMD 控制台而不是使用 Eclipse 的控制台,因为我想尝试做一个简单的动画('|'、'/'、'-'、'\')并且找不到清除的方法Eclipse 控制台上的屏幕。
将我的代码导出到 Runnable Jar 文件后,我在 CMD 控制台上使用 java -jar test.jar 打开它,但我得到了 FileNotFoundException。
为了帮助调试我的代码,我尝试在 Eclipse 上编译它。这是以下输出:
|/-\|/-\|/-\
注意:每个字符串输出之间有 500 毫秒的延迟。
public void doAnimation(String animation) {
try {
BufferedReader br = new BufferedReader(new FileReader( new File("res/animations.txt")));
String current = null;
boolean exit = false;
while((current = br.readLine()) != null && !exit) {
if(current.toLowerCase().equals(animation.toLowerCase())) {
String[] frames = br.readLine().split(" ");
int repeat = 3;
for(int r = 0; r < repeat; r++) {
for(int i = 0; i < frames.length; i++) {
clearConsole();
print(frames[i]);
Thread.sleep(500);
}
}
exit = true;
}
}
br.close();
} catch (FileNotFoundException e) {
print("Could not find animation file.");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
我期待一个简单的旋转棒动画,但它找不到文本文档。
解决方案
确保 jar 文件具有 res/animations.txt 作为顶级目录文件。
使用 this.getClass().getClassLoader().getResoirceAsStream() 获取为文件打开的输入流。
在 Eclipse 的情况下,您放在项目根目录中的任何内容都可以作为相对路径访问。但是当你使用 jar 文件时,你所有的资源必须嵌入到 jar 文件中,以便用作相对路径。
推荐阅读
- python - “或”在 python lambda 中表现异常
- java - 线程“主”java.lang.NoSuchMethodError 中的异常:'void Car.setYear(java.lang.Integer)'
- c - 有没有办法加速 openMP
- machine-learning - 是否可以在训练之前和训练期间修改 OpenAI 健身房状态?
- django - 一个 Django 模板中的多个表单
- oracle - 在这个简单的组中,错误的起别名是错误的原因吗?
- svg - 在 SVG 绘图中将多个子绘图缩放为相同大小
- python - 如何拆分列表并获取python中的最后一个值
- java - 如何在 Java 中使用 Webclient 添加 CA 证书和客户端证书
- php - PHP 在单个会话中可能有多个 file_get_contents 吗?