读取csv中的特定行

enyaitl3  于 2022-12-30  发布在  其他
关注(0)|答案(2)|浏览(163)

有没有什么方法可以根据值来读取特定的行记录。例如,我的csv文件是:

ProductID,ProductName,price,availability,type
12345,Anaox,300,yes,medicine
23456,Chekmeter,400,yes,testing

我想获取ProductID为“23456”的行。我正在检查new CsvReader(“D:\products.csv”).getRawRecord()方法,但它没有任何方法参数。

3lxsmp7m

3lxsmp7m1#

Iterator iterator = CsvReader("D:\\products.csv").Iterator();
while(iterator.hasNext()){
    if((String[] string = (iterator.next))[0] == 23456)
        sout("Found the row: " + string[0] + ", " + string[1] + ", " + string[2] + ", " + string[3] + ", " + string[4]);
}

关于您对性能的担忧:
1.对于1.000个元素,这仍然会比您需要的速度快,当您达到1.000.000个元素时要担心
1.如果你想让Csv的阅读性能更好,你必须使用一种性能更好的方式来存储你的ID。如果你只是在每次创建一个新ID时递增你的ID,并且从不删除一个ID,你可以使用ID作为索引来直接获得正确的行。

jutyujz0

jutyujz02#

public static ArrayList<String> getSpecificRowData(String s) throws IOException 
        {
            String csvFile = s;
            BufferedReader br = null;
            String line = "";
            ArrayList<String> arr=new ArrayList<>();
            try {
                br = new BufferedReader(new FileReader(csvFile));
    
                while ((line = br.readLine()) != null) {
    
                    //write your row name in the given csv file
                    if(line.contains("write your row name"))
                    {
                        arr.add(line);
                    }     
                }
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return arr;  
        }

//return the row in the form of ArrayList

ArrayList<String> li=getSpecificRowData("FileName12.csv");
        System.out.println(li);

相关问题