10

netbeans で Android アプリを開発しています。opencsv を使用して CSV ファイルを読み込もうとしています。ファイルをリソース フォルダーに配置してそこから読み込もうとすると、ビルド中に無効なリソース ディレクトリというエラーが発生します。アプリが起動するたびに読み取れるように、csv ファイルをどこに保存すればよいですか?

4

5 に答える 5

15

csvファイルをassetsフォルダーに配置する必要があります..

InputStreamReader is = new InputStreamReader(getAssets()
                        .open("filename.csv"));

BufferedReader reader = new BufferedReader(is);
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
                        
}
于 2013-11-14T10:13:53.640 に答える
4

別の方法として、uniVocityParsersを見てください。区切りファイルを解析するための膨大な数の方法を提供します。次の例では、Csv ファイル (下の図を参照) を res/raw フォルダーから InputStream オブジェクトに読み込み、それを列形式で読み取ります (key=Column & value=ColumnValues のマップ)。

calendario_bolsa.csv

//Gets your csv file from res/raw dir and load into a InputStream.
InputStream csvInputStream = getResources().openRawResource(R.raw.calendario_bolsa);

//Instantiate a new ColumnProcessor
ColumnProcessor columnProcessor = new ColumnProcessor();

//Define a class that hold the file configuration
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("\n");
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setProcessor(columnProcessor);

//Creates a new CsvParser, passing the settings into its construtor:
CsvParser csvParser = new CsvParser(parserSettings);

//Calls parse method, instantiating an InputStreamReader, passing to its constructor the InputStream object
csvParser.parse(new InputStreamReader(csvInputStream));

//Gets the csv data as a Map of Column / column values.
Map<String, List<String>> columnarCsv = columnProcessor.getColumnValuesAsMapOfNames();

univocityParsers を Android プロジェクトに追加するには:

compile group: 'com.univocity', name: 'univocity-parsers', version: '2.3.0'
于 2016-12-24T05:02:51.047 に答える
2

opencsv の使用:

InputStream is = context.getAssets().open(path);
InputStreamReader reader = new InputStreamReader(is, Charset.forName("UTF-8"));
List<String[]> csv = new CSVReader(reader).readAll();
于 2016-11-02T20:05:30.310 に答える