gpt4 book ai didi

java - 如何查看Java中是否存在资源文件?

转载 作者:IT老高 更新时间:2023-10-28 20:27:12 25 4
gpt4 key购买 nike

我正在尝试将文本输出到 Java 中的资源文件,如下所示:

File file = new File(MLM.class.getClassLoader().getResource("mazes.txt").toString());
BufferedWriter out = new BufferedWriter(new FileWriter(file));
..

但由于资源文件尚未创建,我得到一个空指针异常。如果资源文件尚不存在,如何先创建一个空白资源文件以避免出现此错误?

最佳答案

一个简单的空检查就足够了

URL u = MLM.class.getResource("/mazes.txt");
if (u != null) {
...
}

来自 getResource 的 javadoc

Returns:
A URL object or null if no resource with this name is found

关于java - 如何查看Java中是否存在资源文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9380690/

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