2014-09-21 42 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

相关问题