Java 检查目录中是否存在文件

Java 检查目录中是否存在文件,java,java-8,Java,Java 8,我想用Java读取文件夹中的文件。不幸的是,有时文件丢失,我得到NPE public static HashMap<String, Integer> getCPUTemp() throws IOException { File directory = new File("/sys/devices/virtual/thermal"); if (directory.exists()) { HashMap&l

我想用Java读取文件夹中的文件。不幸的是,有时文件丢失,我得到NPE

public static HashMap<String, Integer> getCPUTemp() throws IOException
    {
        File directory = new File("/sys/devices/virtual/thermal");

        if (directory.exists())
        {
            HashMap<String, Integer> usageData = new HashMap<>();

            File[] fList = directory.listFiles();

            for (File file : fList)
            {
                if (file.isDirectory() && file.getName().startsWith("thermal_zone"))
                {
                    ......................
                }
            }
            return usageData;
        }
        return null;
public static HashMap getCPUTemp()引发IOException
{
文件目录=新文件(“/sys/devices/virtual/thermal”);
if(directory.exists())
{
HashMap usageData=新HashMap();
File[]fList=directory.listFiles();
for(文件:fList)
{
if(file.isDirectory()&&file.getName().startsWith(“热区”))
{
......................
}
}
返回usageData;
}
返回null;
如果文件不存在,我如何防止出现这种情况并返回
null
?您能给我介绍一个使用Java 8的解决方案吗

我在这里获得NPE(文件:fList)

应该是
fList
为空

因此,在创建
fList
之后,选中null

File[] fList = directory.listFiles();
if (fList == null) {
    return null;
}

返回空hashmap而不是null有什么问题吗:返回新的hashmap();我只需要返回null的文件不存在。你从哪里得到NPE?你能检查一下
file.exists()
?我在这里得到NPE
file[]fList=directory.listFiles();
我的错误。我在这里得到NPE
for(file:fList)
好的,我修改了答案。