【问题标题】:Txt file to a 2nd array (bidimensional array)txt 文件到第二个数组(二维数组)
【发布时间】:2014-04-27 20:24:07
【问题描述】:
我正在尝试进行双线性插值,为此我必须读取包含 NxM 维度的 txt 文件。
我需要读取特定行和列的值,我认为有两个选择:
文件用双空格分隔每个值。我假设该文件必须存储在资产上,不是吗?我会感谢任何代码或文档(我不知道)
提前致谢;)
【问题讨论】:
标签:
android
arrays
file
buffer
assets
【解决方案1】:
如果您在使用这些值之前将 txt 文件加载到二维数组中,您的应用程序肯定会运行得更快。从持久存储中打开某些内容比在内存中查找要花费更长的时间。
根据数组的大小,您可能会耗尽内存,这时您需要更加聪明地了解在每个阶段将文件的哪些部分读入内存以进行处理。
StackOverflow 上有很多关于从 Java 中的文本文件中读取二维数组的 questions,在 Android 中应该类似。
【解决方案2】:
您好,我终于读到了一个二维数组:
public double[][] readArray2D(Context c, String file,int rows,int cols) throws IOException {
double [][] data = new double[rows][cols];
int row = 0;
int col = 0;
BufferedReader bufRdr = null;
try {
bufRdr = new BufferedReader(new InputStreamReader(c.getAssets().open(file)));
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
//read each line of text file
try {
while((line = bufRdr.readLine()) != null && row < data.length)
{
StringTokenizer st = new StringTokenizer(line," ");
while (st.hasMoreTokens())
{
//get next token and store it in the array
data[row][col] = Double.parseDouble(st.nextToken());
col++;
}
col = 0;
row++;
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
谢谢大家 ;)