我是Java新手。我想创建将这些值放入这些文件夹的Java代码:

/sys/devices/virtual/thermal/thermal_zone0/temp
/sys/devices/virtual/thermal/thermal_zone1/temp


这是无法正常工作的代码:

public static HashMap<String, HashMap<String, Double>> getTemp() throws IOException
{
    HashMap<String, HashMap<String, Double>> usageData = new HashMap<>();

    File directory = new File("/sys/devices/virtual/thermal");

    File[] fList = directory.listFiles();

    for (File file : fList)
    {
        if (file.isDirectory() && file.getName().startsWith("thermal_zone"))
        {
            File[] listFiles = file.listFiles();
            for (File file1 : listFiles)
            {
                if (file1.isFile() && file1.getName().startsWith("temp"))
                {
                    byte[] fileBytes = null;
                    if (file1.exists())
                    {
                        try
                        {
                            fileBytes = Files.readAllBytes(file1.toPath());
                        }
                        catch (AccessDeniedException e)
                        {
                        }

                        if (fileBytes.length > 0)
                        {
                            HashMap<String, Double> usageData2 = new HashMap<>();

                            String number = file1.getName().replaceAll("^[a-zA-Z]*", "");

                            usageData2.put(number, Double.parseDouble(new String(fileBytes)));

                            usageData.put("data", usageData2);

                        }
                    }
                }
            }
        }
    }
    return usageData;
}


最终结果是这样的:

{data={=80000.0}}


我发现的第一个问题是使用整数存储值时出现错误。
第二个问题是我只能得到一个价值。输出应如下所示:

{data={0=80000.0}}
{data={1=80000.0}}


你能帮我找到问题吗?

最佳答案

file1变量实际上是临时文件。并且由于所有名为temp的文件,以下行将始终导致空字符串“”:

String number = file1.getName().replaceAll("^[a-zA-Z]*", "");


我相信您要使用的文件变量是Thermal_zoneX。我也认为正则表达式是错误的,请尝试以下“ [^ \ d]”,这将删除非数字:

String number = file.getName().replaceAll("[^\\d]", "");


正如您在结果中看到的和我已经解释的那样,您没有值的键,因为数字字符串始终是空字符串:


{data = {= 80000.0}}


要摆脱浮点,请尝试:

HashMap<String, HashMap<String, Int>> usageData = new HashMap<>();


并继续使用解析Double。

10-07 19:08
查看更多