Tomcat 无法读取本地读取的文件

Tomcat cant read file that is read locally

我的 CacheInitializer 中有这段代码实现了 ServletContextListener

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        File file = new File(classLoader.getResource("synonyms.txt").getFile());
        if (file != null && file.exists()) {
            try (Scanner scanner = new Scanner(file)) {
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    String leftHand = line.split("=>")[0];
                    String rightHand = line.split("=>")[1];

                    for (String s : leftHand.split(",")) {
                        if (s.equals(""))
                            continue;
                        synonymsLookupMap.put(s.trim(), rightHand.trim());
                    }
                }
                scanner.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new RuntimeException("Synonyms file not found");
        }

sysnonyms.txt 文件位于资源文件夹中。当我尝试在本地 运行 此代码 (Mac OSX) 时,它 运行 非常好。但是当我在我的 Amazon Linux EC2 机器上部署相同的 war 时,没有读取任何内容。我尝试了远程调试,但代码从未进入 while 循环。也不抛出异常。它找到了文件,但表现得好像它是空的,并且没有要读取的行。我尝试在服务器上通过 vi 创建 synonyms.txt 然后使用它来查看它是否是文件格式问题。也没用。

知道一定是什么问题吗?

资源不是文件。资源 API 可以为您提供 URL 或资源的 InputStream。这就是你所需要的。只需直接从输入流构造 Scanner 即可。通过文件转移是多余的,没有意义的,不会起作用。