来自CSV的Android换行字符串



我正在构建一个Android应用程序,我想从CSV文件中读取数据,并将其显示在一些文本视图中。最后一列可以有一个更大的文本,其中有换行符。

示例CSV行,我正在读取字符串数组:

Cat1; Cat2; Sample Textnwith a line break

在将字符串设置为文本视图的文本后,我将在设备/模拟器上得到这个:

带换行的示例文本

如果我像这样直接设置字符串:

textView.setText("Sample Textnwith a line break");

或者,如果我像这样替换一个不同的占位符:
(CSV中的字符串:带换行符的示例文本zzz(

textView.setText(someArray[2].replace("zzz", "n"));

它会给我带来想要的结果:

带换行的示例文本

我也尝试过.replace(",","(,但这也没有帮助
我做错了什么?这可能是一些基本的东西
我自己提供CSV,所以我也可以更改其中的某些内容。

提前谢谢。

第1版:这就是我将CSV读取为字符串数组的方式

int choosenfile = getResources().getIdentifier("test", "raw", getPackageName());
InputStream is = getResources().openRawResource(choosenfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String line = "";
try{
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(";", -1);
someArray[0] = tokens[0];
someArray[1] = tokens[1];
someArray[2] = tokens[2];
}
} catch (IOException e1) {
Log.e("MainActivity", "Error" + line, e1);
e1.printStackTrace();
}

给定一个包含以下内容的文件res/raw/data.csv

Cat1; Cat2; Sample Textnwith a line break

以及下面的Java代码

String[] someArray = new String[3];
InputStream is = getResources().openRawResource(R.raw.data);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String line = "";
try{
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(";", -1);
someArray[0] = tokens[0];
someArray[1] = tokens[1];
someArray[2] = tokens[2];
}
} catch (IOException e1) {
Log.e("MainActivity", "Error" + line, e1);
e1.printStackTrace();
}

TextView tv = findViewById(R.id.textView);
tv.setText(someArray[2].replace("\n", "n"));

它按预期工作。

但是,您可能需要考虑以下因素来轻松处理CSV文件:https://stackoverflow.com/a/43055945/2232127


此外,您的当前循环将在每次迭代中覆盖someArray,导致只包含文件中最后一行的数据。此外,请确保在使用完流后关闭它们。

最新更新