2014-09-21 44 views
1

我想將文本文件讀入我的android程序並將內容存儲在類的向量中。的文本文件的內容的示例如下所示:如何讀取文本文件並存儲在類的向量中 - Android

Latitude Longitude Radioactivity 
56.0349 -3.34267 8690000 
56.0328 -3.342  867289 
56.0328 -3.342  867289 
56.0348 -3.34242 404430 
56.0348 -3.34247 295287 
56.0338 -3.34122 221830 
56.0346 -3.34242 193347 
56.0337 -3.34118 182304 
56.0342 -3.34141 155572 
56.0337 -3.34173 145229 
56.0347 -3.34239 125143 

我要存儲在一個矢量這些值(或陣列,因爲該列表的長度是有限的),這樣我可以在一個訪問列表for循環將用戶當前位置與點列表進行比較(如geofencing除了我有一個點的數據庫)。

我已經在C++中完成了這個工作,但是我之前沒有在java中編程,這是我的第一個android應用程序。以下是我的C++代碼。我的問題是,我如何在我的android應用程序在java中做同樣的事情?

#include <iostream> 
#include <string> 
#include <sstream> 
#include <fstream> 
#include <vector> 
#include <iomanip> 

using namespace std; 

struct radioactivityData 
{ 
double lat; 
double lon; 
int radioactivity; 
}; 

int main() 
{ 
std::ifstream dataFile; 
dataFile.open("combinedorderedData.txt"); 

std::string tmpLine; 
std::vector<radioactivityData> radioactivityTable; 

while(std::getline(dataFile, tmpLine)) 
{ 
    std::stringstream inputLine(tmpLine); 

    radioactivityData rad; 
    if(!(inputLine >> rad.lat >> rad.lon >> rad.radioactivity)) 
    { 
     // ... error parsing input. Report the error 
     // or handle it in some other way. 

     continue; // keep going! 
    } 
    radioactivityTable.push_back(rad); 
} 

回答

1

這裏是逐行讀取文件中的行的一般方法:

private void processFile(Context context, String fileName) { 
    BufferedReader br; 

    File file = new File(context.getExternalFilesDir(null) + "/" + FILE_DIR, fileName); 
    try { 
     FileReader fr = new FileReader(file); 
     br = new BufferedReader(fr); 
    } catch (FileNotFoundException e) { 
     Log.e("couldn't read from external file"); 
     return; 
    } 

    try { 
     String line; 
     while ((line = br.readLine()) != null) { 
      // here you put your code 
      processLine(line); 
     } 
    } catch (IOException e) { 
     Log.e("couldn't process line"); 
    } finally { 
     try { 
      if (br != null) { 
       br.close(); 
      } 
     } catch (IOException e) { 
      Log.e("Failed to close BufferedReader"); 
     } 
    } 
} 

假設你有一個方法來創建從線串所需RadioactivityData對象:

private ArrayList<RadioactivityData> mRadioactivityList = new ArrayList<RadioactivityData>(); 

private void processLine(String line) { 

    RadioactivityData radioactivityData = new RadioactivityData(line); 
    mRadioactivityList.add(radioactivityData); 
} 
+0

感謝你的答案,但我還需要將數據存儲在構造函數中,就像在我的C++代碼中一樣。 – Pixelsoldier 2014-09-21 09:05:10

+0

編輯答案。您可以將數據存儲在ArrayList中。 – ziv 2014-09-21 09:40:30

+0

所以在第一個代碼塊中,它說//在這裏您放置代碼,是我需要解析數據並將其存儲在mRadioactivityList的相關部分中的地方。此外,你說「假設你有一種方法來從行字符串創建所需的RadioactivityData對象」。你什麼意思?我必須在Java中創建對象,類似於我在C++代碼中的做法嗎?對不起,我對java和android開發非常陌生,但我需要在星期一做我的程序:S – Pixelsoldier 2014-09-21 09:46:52

相關問題