我想将一个文本文件读入我的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循环中访问列表,将用户当前位置与点列表进行比较(如地理围栏除外)我有一个积分数据库。)
我已经用c ++完成了这个,但我之前没有在java中编程,这是我的第一个Android应用程序。下面是我的c ++代码。我的问题是,我如何在java中为我的Android应用程序做同样的事情?
#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);
}
答案 0 :(得分: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);
}