Android读取CSV文件遇ENOENT错误:找不到raw/players.csv文件求助
问题诊断与解决方案
1. 文件找不到错误的核心原因
Android项目中,res/raw目录下的资源是打包进APK的,并非存储在设备的文件系统路径中,直接用FileReader("raw/players.csv")无法定位到文件。
2. 修正CSV读取逻辑
改用Android原生资源API读取raw文件,同时修复代码中存在的索引越界问题:
public class PlayerManager { // 新增Context参数用于获取资源 public static List<List<String>> getSixRandomPlayers(Context context, String position) { List<List<String>> players = readPlayersFromCSV(context); List<List<String>> filteredPlayers = filterPlayersByPosition(players, position); return selectRandomPlayers(filteredPlayers, 6); } private static List<List<String>> readPlayersFromCSV(Context context) { List<List<String>> players = new ArrayList<>(); // 通过openRawResource获取raw资源输入流 try (BufferedReader reader = new BufferedReader( new InputStreamReader(context.getResources().openRawResource(R.raw.players)))) { String line; while ((line = reader.readLine()) != null) { String[] playerData = line.split(","); List<String> player = new ArrayList<>(); player.add(playerData[0]); // 第1列 player.add(playerData[2]); // 第3列 player.add(playerData[6]); // 第7列 player.add(playerData[13]); // 第14列 player.add(playerData[7]); // 第8列 player.add(playerData[16]); // 第17列(原注释写错,数组索引16对应第17列) players.add(player); } } catch (IOException e) { e.printStackTrace(); } return players; } // 修复索引越界:read方法仅存入6个元素,索引范围是0-5,第17列对应索引5 private static List<List<String>> filterPlayersByPosition(List<List<String>> players, String position) { List<List<String>> filteredPlayers = new ArrayList<>(); for (List<String> player : players) { if (player.size() > 5 && player.get(5).equals(position)) { filteredPlayers.add(player); } } return filteredPlayers; } // 优化随机逻辑:避免修改原集合,复制后再打乱 private static List<List<String>> selectRandomPlayers(List<List<String>> players, int count) { List<List<String>> shuffledPlayers = new ArrayList<>(players); Collections.shuffle(shuffledPlayers); int takeCount = Math.min(count, shuffledPlayers.size()); return shuffledPlayers.subList(0, takeCount); } }
3. 额外注意事项
- 资源文件校验:确保
res/raw/players.csv存在,文件名需小写,无空格或特殊字符。 - CSV解析严谨性:用
split(",")处理CSV存在缺陷,若字段包含逗号(如"Smith, John")会拆分错误,建议使用专业CSV库,比如在build.gradle添加OpenCSV依赖:
用OpenCSV读取的示例:implementation 'com.opencsv:opencsv:5.6'private static List<List<String>> readPlayersFromCSV(Context context) { List<List<String>> players = new ArrayList<>(); try (CSVReader reader = new CSVReader( new InputStreamReader(context.getResources().openRawResource(R.raw.players)))) { String[] nextLine; reader.readNext(); // 跳过表头(如果CSV有表头的话) while ((nextLine = reader.readNext()) != null) { List<String> player = new ArrayList<>(); player.add(nextLine[0]); player.add(nextLine[2]); player.add(nextLine[6]); player.add(nextLine[13]); player.add(nextLine[7]); player.add(nextLine[16]); players.add(player); } } catch (IOException e) { e.printStackTrace(); } return players; } - 异常防护:添加集合长度检查,避免因CSV格式错误导致索引越界崩溃。
内容的提问来源于stack exchange,提问作者Eduard Atoyan
相关产品推荐
相关产品推荐

