首页 > 解决方案 > 使用不同的控制台时找不到文本文档

问题描述

我尝试使用 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();
        }
    }

我期待一个简单的旋转棒动画,但它找不到文本文档。

标签: javaeclipse

解决方案


确保 jar 文件具有 res/animations.txt 作为顶级目录文件。

使用 this.getClass().getClassLoader().getResoirceAsStream() 获取为文件打开的输入流。

在 Eclipse 的情况下,您放在项目根目录中的任何内容都可以作为相对路径访问。但是当你使用 jar 文件时,你所有的资源必须嵌入到 jar 文件中,以便用作相对路径。


推荐阅读