如何在Android中导入和显示csv文件数据

l0oc07j2  于 2022-12-06  发布在  Android
关注(0)|答案(1)|浏览(225)

我正在做一个项目,我需要从内部存储导入CSV文件,并在Android中的同一活动中显示数据。

w8ntj3qf

w8ntj3qf1#

尝试以下代码

public class CSVReader {
    Context context;
    String fileName;
    List<String[]> rows = new ArrayList<>();

    public CSVReader(Context context, String fileName) {
        this.context = context;
        this.fileName = fileName;
    }

    public List<String[]> readCSV() throws IOException {
        InputStream is = context.getAssets().open(fileName);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        String csvSplitBy = ",";

        br.readLine();

        while ((line = br.readLine()) != null) {
            String[] row = line.split(csvSplitBy);
            rows.add(row);
        }
        return rows;
    }
}

以上类使用如下

public class MainActivity extends AppCompatActivity {
    RatingBar ratingBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<String[]> rows = new ArrayList<>();
        CSVReader csvReader = new CSVReader(RatingActivity.this, "movies.csv");
        try {
            rows = csvReader.readCSV();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < rows.size(); i++) {
            Log.d(Constants.TAG, String.format("row %s: %s, %s", i, rows.get(i)[0], rows.get(i)[1]));
        }
    }
}

相关问题