不打印所有文件

时间:2015-03-03 12:27:57

标签: java regex

我是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}}

你能帮我找到问题吗?

1 个答案:

答案 0 :(得分:1)

file1变量实际上是临时文件。并且因为名为temp的所有文件,以下行总是会产生空字符串&#34;&#34;:

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

我相信你想使用的文件变量是thermal_zoneX。我也认为正则表达式是错误的尝试以下&#34; [^ \ d]&#34;,这将删除非数字:

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

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

  

{数据= {= 80000.0}}

摆脱浮点试试:

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

继续使用解析Double。

相关问题