我正在使用 OpenCSV 读取存储在设备内部存储器中的名为 product.csv
的 CSV 文件 \G Shop\Input CSV\
。该文件包含一些随机产品名称的单列。我想将每个产品存储到一个 ArrayList
中,但我的代码不起作用。
代码如下:
String baseDirectory = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
File readCsvFolder = new File(baseDirectory + File.separator + "G Shop" + File.separator + "Input CSV" + File.separator);
String readFileName;
String readFilePath;
List<String[]> readData;
void readCSV() {
readCsvFolder.mkdirs();
readFileName = "products.csv";
readFilePath = readCsvFolder.getPath() + File.separator + readFileName;
try {
ArrayList<String> searchProducts = new ArrayList<>();
readData = new ArrayList<String[]>();
CSVReader reader = new CSVReader(new FileReader(readFilePath));
readData = reader.readAll();
String[] row;
while ((row = reader.readNext()) != null) {
searchProducts.add(row[0]);
//This Toast never shows up!
Toast.makeText(mainActContext,"Saved : " + row[0],Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
我没有看到错误或警告,调用方法后根本没有输出。我将非常感谢任何形式的帮助或建议:)
最佳答案
readData = reader.readAll();
正在读取整个文件输入流,直到文件结束。因此 row = reader.readNext()) != null
从一开始就不会给你任何东西;读者已经到达文件末尾。相反,您的循环可以简单地是:for(String[] row:readData)
:
for(String[] row:readData) {
searchProducts.add(row[0]);
//Now the toast shows up!
Toast.makeText(mainActContext,"Saved : " + row[0],Toast.LENGTH_SHORT).show();
}
关于java - 从 CSV 读取并将数据存储到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005318/