2015-03-03 225 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