web-dev-qa-db-fra.com

Lire le fichier CSV colonne par colonne

Je souhaite lire des colonnes spécifiques d'un fichier CSV à plusieurs colonnes et les imprimer dans un autre fichier CSV à l'aide de Java. Toute aide s'il vous plaît? Voici mon code pour imprimer chaque jeton ligne par ligne.

import Java.io.BufferedReader;
import Java.io.FileReader;
import Java.io.FileWriter;
import Java.util.StringTokenizer;

public class ParseCSV {

    public static void main(String[] args) {

        try
        {

            //csv file containing data
            String strFile = "C:\\Users\\rsaluja\\CMS_Evaluation\\Drupal_12_08_27.csv";

            //create BufferedReader to read csv file
            BufferedReader br = new BufferedReader( new FileReader(strFile));
            String strLine = "";
            StringTokenizer st = null;
            int lineNumber = 0, tokenNumber = 0;

            //read comma separated file line by line
            while( (strLine = br.readLine()) != null)
            {
                lineNumber++;

                //break comma separated line using ","
                st = new StringTokenizer(strLine, ",");

                while(st.hasMoreTokens())
                {
                //display csv values
                tokenNumber++;
                System.out.println("Line # " + lineNumber +
                                ", Token # " + tokenNumber
                                + ", Token : "+ st.nextToken());


                            System.out.println(cols[4]);
22
drupal_dev

Vous devez utiliser l'excellent OpenCSV pour lire et écrire des fichiers CSV. Pour adapter votre exemple à utiliser la bibliothèque, cela ressemblerait à ceci:

public class ParseCSV {
  public static void main(String[] args) {
    try {
      //csv file containing data
      String strFile = "C:/Users/rsaluja/CMS_Evaluation/Drupal_12_08_27.csv";
      CSVReader reader = new CSVReader(new FileReader(strFile));
      String [] nextLine;
      int lineNumber = 0;
      while ((nextLine = reader.readNext()) != null) {
        lineNumber++;
        System.out.println("Line # " + lineNumber);

        // nextLine[] is an array of values from the line
        System.out.println(nextLine[4] + "etc...");
      }
    }
  }
}
42
Jason Sperske

Je suis désolé, mais aucune de ces réponses ne fournit une solution optimale. Si vous utilisez une bibliothèque telle que OpenCSV, vous devrez écrire beaucoup de code pour gérer les cas particuliers afin d'extraire des informations de colonnes spécifiques.

Par exemple, si vous avez des lignes avec moins de colonnes que ce que vous recherchez, vous devrez écrire beaucoup de code pour le gérer. En utilisant l'exemple OpenCSV:

  CSVReader reader = new CSVReader(new FileReader(strFile));
  String [] nextLine;
  while ((nextLine = reader.readNext()) != null) {
       //let's say you are interested in getting columns 20, 30, and 40
       String[] outputRow = new String[3];
       if(parsedRow.length < 40){
            outputRow[2] = null;
       } else {
            outputRow[2] = parsedRow[40]
       }
       if(parsedRow.length < 30){
            outputRow[1] = null;
       } else {
            outputRow[1] = parsedRow[30]
       }
       if(parsedRow.length < 20){
            outputRow[0] = null;
       } else {
            outputRow[0] = parsedRow[20]
       }

  }

C'est beaucoup de code pour une simple exigence. Cela empire si vous essayez d'obtenir les valeurs des colonnes par leur nom. Vous devez utiliser un analyseur plus moderne, tel que celui fourni par uniVocity-parsers .

Pour obtenir de manière fiable et simple les colonnes souhaitées, écrivez simplement:

CsvParserSettings settings = new CsvParserSettings();
parserSettings.selectIndexes(20, 30, 40);
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader(yourFile));

Divulgation: Je suis l'auteur de cette bibliothèque. Il est open-source et gratuit (licence Apache V2.0).

4
Jeronimo Backes

Je suggère d'utiliser Apache Commons CSV https://commons.Apache.org/proper/commons-csv/

Voici un exemple:

    Path currentRelativePath = Paths.get("");
    String currentPath = currentRelativePath.toAbsolutePath().toString();
    String csvFile = currentPath + "/pathInYourProject/test.csv";

    Reader in;
    Iterable<CSVRecord> records = null;
    try
    {
        in = new FileReader(csvFile);
        records = CSVFormat.Excel.withHeader().parse(in); // header will be ignored
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    for (CSVRecord record : records) {
        String line = "";
        for ( int i=0; i < record.size(); i++)
        {
            if ( line == "" )
                line = line.concat(record.get(i));
            else
                line = line.concat("," + record.get(i));
        }
        System.out.println("read line: " + line);
    }

Il reconnaît automatiquement , et " mais pas ; (peut-être peut-il être configuré ...).

Mon exemple de fichier est:

col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"

Et la sortie est:

read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"

La dernière ligne est considérée comme une valeur.

1
Andreas L.

Pour lire une colonne spécifique, j'ai fait quelque chose comme ceci:

dpkcs.csv content:
FN,LN,EMAIL,CC
Name1,Lname1,[email protected],CC1
Nmae2,Lname2,[email protected],CC2

La fonction pour le lire:

private void getEMailRecepientList() {
                List<EmailRecepientData> emailList = null;// Blank list of POJO class
                Scanner scanner = null;
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader("dpkcs.csv"));
                    Map<String, Integer> mailHeader = new HashMap<String, Integer>();
                    // read file line by line
                    String line = null;
                    int index = 0;
                    line = reader.readLine();
                    // Get header from 1st row of csv
                    if (line != null) {
                        StringTokenizer str = new StringTokenizer(line, ",");
                        int headerCount = str.countTokens();
                        for (int i = 0; i < headerCount; i++) {
                            String headerKey = str.nextToken();
                            mailHeader.put(headerKey.toUpperCase(), new Integer(i));

                        }
                    }
                    emailList = new ArrayList<EmailRecepientData>();

                    while ((line = reader.readLine()) != null) {
                    // POJO class for getter and setters
                        EmailRecepientData email = new EmailRecepientData();
                        scanner = new Scanner(line);
                        scanner.useDelimiter(",");
                    //Use Specific key to get value what u want
                        while (scanner.hasNext()) {
                            String data = scanner.next();
                            if (index == mailHeader.get("EMAIL"))
                                email.setEmailId(data);
                            else if (index == mailHeader.get("FN"))
                                email.setFirstName(data);
                            else if (index == mailHeader.get("LN"))
                                email.setLastName(data);
                            else if (index == mailHeader.get("CC"))
                                email.setCouponCode(data);

                            index++;
                        }
                        index = 0;
                        emailList.add(email);
                    }
                    reader.close();
                } catch (Exception e) {
                    StringWriter stack = new StringWriter();
                    e.printStackTrace(new PrintWriter(stack));

                } finally {
                    scanner.close();
                }

                System.out.println("list--" + emailList);

            }

La classe POJO:

public class EmailRecepientData {
    private String emailId;
    private String firstName;
    private String lastName;
    private String couponCode;

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getCouponCode() {
        return couponCode;
    }

    public void setCouponCode(String couponCode) {
        this.couponCode = couponCode;
    }

    @Override
    public String toString() {
        return "Email Id=" + emailId + ", First Name=" + firstName + " ,"
                + " Last Name=" + lastName + ", Coupon Code=" + couponCode + "";
    }

}
1
dpkcs

Trouve tous les fichiers du dossier et écrit ces données dans la ligne ArrayList.

Initialiser

ArrayList<ArrayList<String>> row=new ArrayList<ArrayList<String>>();
BufferedReader br=null;

Pour accéder à la ligne

for(ArrayList<String> data:row){
data.get(col no); 
}
or row.get(0).get(0) // getting first row first col

Fonctions qui lisent tous les fichiers des dossiers et les concaténent.

static void readData(){
String path="C:\\Users\\Galaxy Computers\\Desktop\\Java project\\Nasdaq\\";
File files=new File(path);
String[] list=files.list();

try {
        String sCurrentLine;
       char check;
       for(String filename:list){ 
        br = new BufferedReader(new FileReader(path+filename));
        br.readLine();//If file contains uneccessary first line.
        while ((sCurrentLine = br.readLine()) != null) {

           row.add(splitLine(sCurrentLine));
        }
        }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } 
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


   static ArrayList<String> splitLine(String line){
   String[] ar=line.split(",");
   ArrayList<String> d=new ArrayList<String>();
   for(String data:ar){
    d.add(data);
   }

   return d; 
   } 
0
Ali khan

Eh bien, que diriez-vous de ça !!

Ce code calcule le nombre de lignes et de colonnes dans un fichier csv. Essayez ceci !!

    static int[] getRowsColsNo() {
    Scanner scanIn = null;
    int rows = 0;
    int cols = 0;
    String InputLine = "";
    try {
        scanIn = new Scanner(new BufferedReader(
                new FileReader("filename.csv")));
        scanIn.useDelimiter(",");
        while (scanIn.hasNextLine()) {
            InputLine = scanIn.nextLine();
            String[] InArray = InputLine.split(",");
            rows++;
            cols = InArray.length;
        }

    } catch (Exception e) {
        System.out.println(e);
    }
    return new int[] { rows, cols };
}
0
ronypatil

Nous pouvons utiliser le seul matériel Java pour lire le fichier CVS colonne par colonne. Voici l'exemple de code que j'ai écrit pour mon besoin. Je crois que cela aidera pour quelqu'un.

 BufferedReader br = new BufferedReader(new FileReader(csvFile));
    String line = EMPTY;
    int lineNumber = 0;

    int productURIIndex = -1;
    int marketURIIndex = -1;
    int ingredientURIIndex = -1;
    int companyURIIndex = -1;

    // read comma separated file line by line
    while ((line = br.readLine()) != null) {
        lineNumber++;
        // use comma as line separator
        String[] splitStr = line.split(COMMA);
        int splittedStringLen = splitStr.length;

        // get the product title and uri column index by reading csv header
        // line
        if (lineNumber == 1) {
            for (int i = 0; i < splittedStringLen; i++) {
                if (splitStr[i].equals(PRODUCTURI_TITLE)) {
                    productURIIndex = i;
                    System.out.println("product_uri index:" + productURIIndex);
                }

                if (splitStr[i].equals(MARKETURI_TITLE)) {
                    marketURIIndex = i;
                    System.out.println("marketURIIndex:" + marketURIIndex);
                }

                if (splitStr[i].equals(COMPANYURI_TITLE)) {
                    companyURIIndex = i;
                    System.out.println("companyURIIndex:" + companyURIIndex);
                }

                if (splitStr[i].equals(INGREDIENTURI_TITLE)) {
                    ingredientURIIndex = i;
                    System.out.println("ingredientURIIndex:" + ingredientURIIndex);
                }
            }
        } else {
            if (splitStr != null) {
                String conditionString = EMPTY;
                // avoiding arrayindexoutboundexception when the line
                // contains only ,,,,,,,,,,,,,
                for (String s : splitStr) {
                    conditionString = s;
                }
                if (!conditionString.equals(EMPTY)) {
                    if (productURIIndex != -1) {
                        productCVSUriList.add(splitStr[productURIIndex]);
                    }
                    if (companyURIIndex != -1) {
                        companyCVSUriList.add(splitStr[companyURIIndex]);
                    }
                    if (marketURIIndex != -1) {
                        marketCVSUriList.add(splitStr[marketURIIndex]);
                    }
                    if (ingredientURIIndex != -1) {
                        ingredientCVSUriList.add(splitStr[ingredientURIIndex]);
                    }
                }
            }
        }
0
Devi