例如resources下有vote.csv文件,可以用下面的方法进行读取处理

    private List<List<String>> readUserFile(int userSize) {
        List<List<String>> data = new ArrayList<>();
        String[] nextLine;
        int count = 0;
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("vote.csv");
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            while ((nextLine = new String[] {bufferedReader.readLine()}) != null && count < userSize) {
                //逐行读取数据,存储在一个List中
                List<String> lineData = new ArrayList<>();
                for (String d : nextLine) {
                    lineData.add(d);
                }
                data.add(lineData);
                count++;
            }
            System.out.println("---data = " + data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

注意⚠️:如果用绝对路径直接操作文件,会出现打成jar包后文件的绝对路径变化,导致获取不到对应的文件而报错。转成IO流来操作会更稳。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐