gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:51:35 25 4
gpt4 key购买 nike

我的 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 即可。通过文件转移是多余的和毫无意义的,不会起作用。

关于java - Tomcat无法读取本地读取的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com