我正在构建一个Android应用程序,我想从CSV文件中读取数据,并将其显示在一些Textviews中。最后一列可以有一个较大的文本,其中包含行符。
示例CSV行,我正在读取一个字符串数组:
Cat1; Cat2; Sample Text\nwith a line break在将字符串设置为文本视图后,我将在设备/模拟器中获得以下内容:
示例文本\n带行中断
如果我像这样直接设置字符串:
textView.setText("Sample Text\nwith a line break");或者,如果我换了一个不同的地方,像这样:
(CSV中的字符串:带有行中断的示例Textzzzwith )
textView.setText(someArray[2].replace("zzz", "\n"));它会给我带来预期的结果:
样本文本
断线
我也尝试了.replace("\n","\n"),但是这也没有帮助。
我做错了什么?可能是一些基本的东西。
我自己提供CSV,这样我也可以在里面改变一些东西。
提前谢谢。
Edit1:如何将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();
}发布于 2021-01-02 20:23:44
给定一个包含以下内容的文件res/raw/data.csv:
Cat1; Cat2; Sample Text\nwith 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,结果只包含文件中最后一行的数据。另外,当您使用完流时,请确保关闭它们。
https://stackoverflow.com/questions/65543163
复制相似问题