且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何提取.CSV文件中的特定行?

更新时间:2023-01-15 19:11:52

您需要的不是嵌套循环,而是 Arrays.toString 方法.

What you need is just not a nested loop, just a Arrays.toString method.

import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.opencsv.CSVReader;


public class Test {
    public static void main(String[] arg){
        search();
    }
    public static void search(){
        try{

            String strSearch = "banana";

            CSVReader reader = new CSVReader(new FileReader("d:\\textfile.txt"), ',');
            List<String[]> myEntries = reader.readAll();
            System.out.println(myEntries.size());
            reader.close();

            //Write to existing file
            //CSVWriter writer = new CSVWriter(new FileWriter("test.txt"), ',',CSVWriter.NO_QUOTE_CHARACTER, "\r\n");

            //Iterate through my array to find the row the user input is located on
            int i=1;
            for (String[] line : myEntries)
            {

                String textLine = Arrays.toString(line).replaceAll("\\[|\\]","");
                System.out.println(textLine);
                  if (textLine.contains(strSearch))
                    {
                        //Need a method so I can find out what row my item is on
                        System.out.println("Found - Your item is on row: ...:"+i);

                        //Code to extract row into something (String array?) so I can edit it's contents

                        //I then need to write the edited row back to it's original row

                    }else
                    {
                        System.out.println("Not found");
                    }
                  i++;
            }

       }catch (IOException e)
            {
                System.out.println(e);
            }
    }
}