gpt4 book ai didi

java - 如何读取文本文件并存储在类 vector 中 - Android

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:59 26 4
gpt4 key购买 nike

我想将文本文件读入我的 android 程序并将内容存储在类 vector 中。文本文件的内容示例如下所示:

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

我想将这些值存储在一个 vector 中(或者一个数组,因为列表的长度是有限的),这样我就可以在 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);
}

最佳答案

这是一种逐行读取文件的通用方法:

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);
}

关于java - 如何读取文本文件并存储在类 vector 中 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25957356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com