2015-03-03 85 views
0

我是新来的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}} 

你能帮我找到问题吗?

+0

您不能使用同一个键将两个值插入* normal *映射。这个'usageData.put(“data”,usageData2);'替换之前用关键字''data''存储的值。您可以改用[Multimap](https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap)。 – Tom 2015-03-03 12:34:27

+0

尝试从'HashMap'切换到'ArrayList'。 – 2015-03-03 12:35:05

+0

关于第二个问题?你知道为什么当我尝试使用usageData2.put(number,Integer.parseInt(new String(fileBytes)));' – user1285928 2015-03-03 12:38:45

回答

1

file1变量实际上是临时文件。因为所有的文件名为temp以下行总是导致空字符串“”:

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

我相信你要使用的文件变量,它是thermal_zoneX。我也觉得正则表达式是错误的请尝试以下“[^ \ d]”,这将删除非数学运算:

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

正如你可以在这里看到的结果和我解释,你有没有密钥值,因为数字字符串总是一个空字符串:

{数据= {= 80000.0}}

摆脱浮点试试:

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

并继续使用解析Double。

+0

我得到这个结果:'{_zone1 = {_ zone1 = 73000.0},_zone0 = {_ zone0 = 61000.0}}'出于某种原因,我也得到_zone,这是不需要的。你知道我可以如何删除它吗? – user1285928 2015-03-03 12:44:31

+0

那么现在的问题是与正则表达式 – hasan83 2015-03-03 12:45:49

+0

谢谢你和最后一个问题。你有什么想法,为什么我不能使用Integer这个代码:usageData2.put(number,Integer.parseInt(new String(fileBytes)));我得到错误java.lang.NumberFormatException:对于输入字符串:“74000 – user1285928 2015-03-03 12:50:51