gpt4 book ai didi

android - 如何从文本文件中读取并存储到android中的数组中

转载 作者:行者123 更新时间:2023-11-29 17:49:18 29 4
gpt4 key购买 nike

friend 们

我正在开发一个 android 应用程序,该文本文件应该用一些数字生成。在此之后,一个接一个的应用程序应调用该号码。

例如:

9876452125,9876452135,9876452115,

大多数情况下,该文本文件有 8 个数字,由“,”和换行符“\n”分隔

现在我想逐行读取该文件。

我的读取文件和存储到数组的代码是:

public void read(String fname)
{
BufferedReader br = null;
try
{
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/" + fname + ".txt";
br = new BufferedReader(new FileReader(fpath));
String line = null;
int index = 0;

String[][] num = new String[15][10];

List<String[]> collection = new ArrayList<String[]>();
while ((line = br.readLine()) != null)
{
if (index < num.length)
{

output.append(line);
// output.append("\n");

num[index] = line.split(",");

if (num.length > 0)
{
collection.add(num[index]);
}
}
Toast.makeText(getApplicationContext(), "" + collection, 5000)
.show();
index++;

}
}
catch (IOException e)
{
e.printStackTrace();
}
}

现在我的问题是,当我将集合打印到 Toast 时,它会显示一些随机字符串。不知道为什么??

是否有人对如何逐行读取文件并存储到数组有正确的想法或示例代码。

谢谢分配。

最佳答案

如果我是你,我会使用扫描仪。您没有提供有关计划如何存储它们的信息:例如,为什么使用 String[][] num = new String[15][10];,但我会给您一个例子,如果你想把每个数字存储在它自己的元素中,你可以在必要时进行调整(我假设你的文件中每一行的末尾只有一个换行符)。

public void read(String fname) {
String fpath = "/sdcard/" + fname + ".txt";
File file = new File(fpath);
Scanner scanner = new Scanner(new FileInputStream(file));
List<String[]> collection = new ArrayList<String[]>();

while (scanner.hasNextLine()){
String line = scanner.nextLine();
String.replaceAll("\n", ""); // strip the newline
String[] myList = myString.split(",");
for (i=0; i < myList.length; i++) {
collection.add(myList[i]);
}
}
scanner.close();
}

这里面没有任何 android 元素,但就像我说的,您可以根据需要进行调整以执行您特别需要它执行的操作。

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

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