简体   繁体   中英

parsing a csv file using java

I'm a beginner when it comes to Java and I'm trying to pull these values vertically and store them in a data type with their reference. So "A" would have 1,8,7,6 mapped to it and the dates in front would be excluded as well. The csv file is below.

10/1/14, A,B,C,D,E,F,G,H

10/2/14, 1,2,3,4,5,6,7,8

10/3/14, 8,1,2,3,4,5,6,7

10/4/14, 7,8,1,2,3,4,5,6

10/5/14, 6,7,8,1,2,3,4,5

Here is my code. So far I've been able to grab the rows individually, but I'm I don't know how to add them to a data structure. This would return >> C3218

    class Main {
        public static void main(String[] args) {
            Read r = new Read();
            r.openFile();
            r.readFile();
            r.closeFile();

        }
    }

        import java.io.*;
        import java.util.*;
        public class Read {

        private Scanner x;
        public void openFile() {
            try {
                x = new Scanner(new File("test.csv"));
            }
            catch(Exception e){
                System.out.println("could not find file");
            }

            }
        public void readFile() {
            while(x.hasNext()){
                String a = x.next();
                String[] values = a.split(",");
                System.out.printf(values[3]); // gets line
            }
        }
        public void closeFile() {
            x.close();
        }
}

Java is an Object Oriented programming language. I'm going to assume that what you call "data structures" are Objects in Java parlance. For example (and these are just examples, not something you specifically could use for your situation), if I want to represent a person, I might have something like this

public interface Person{
    String getName();
    Date getBirthDate();
}

public class GenericPerson implements Person{
    private final String name;
    private final Date bdate;

    public GenericPerson(String fullName, Date birthdate){
        name = fullName;
        bdate = birthdate;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Date getBirthDate() {
        return bdate;
    }
}

Pretty sparse, but I'm just trying to show some basic concepts.

You asked

I don't know how to add them to a data structure.

In my example, you would instantiate a GenericPerson

Person p = new GenericPerson(name,date);

Of course, you'll need the name and date variables. That's where the parsing the file comes in. So if I had a file of the form

George Costanza,5/4/1956
Cosmo Kramer,12/12/1960
Jerry Seinfeld,1/2/1959

Then in my code to parse the file I might have

String line = scanner.next();
String[] values = line.split(",");
Person p = new GenericPerson(values[0],getDateFormatter().parse(values[1]));

So you create your Object type, defining what fields you want it to have. And then populate them via a constructor or setter methods. An example of setter methods would be if I modified the GenericPerson like this

public class GenericPerson implements Person{
    private String name;
    private Date bdate;

    public void setName(String n){
        name = n;
    }

    public void setBirthDate(Date d){
        bdate = d;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Date getBirthDate() {
        return bdate;
    }
}

Now I would need to call those to set the values in the Object .

For your case, you'll need to define some Object type that the data is meant to define. The type will have fields like the GenericPerson and you need to have setter methods or a constructor that takes arguments corresponding to the fields.

I highly recommend following the online tutorial for java beginners.

It took me 30 minutes just to get your code to compile and run correctly.

I used a List of a Column class that I created. The Column class contains the name of the column and the values in that CSV column.

The test.csv file is in the same directory as the Java class.

Here's the results.

A: 1, 8, 7, 6
B: 2, 1, 8, 7
C: 3, 2, 1, 8
D: 4, 3, 2, 1
E: 5, 4, 3, 2
F: 6, 5, 4, 3
G: 7, 6, 5, 4
H: 8, 7, 6, 5 

And here's the code.

package com.ggl.testing;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CSVColumns implements Runnable {

    public static void main(String[] args) {
        new CSVColumns().run();
    }

    @Override
    public void run() {
        Scanner scanner = openFile();
        if (scanner != null) {
            readFile(scanner);
            closeFile(scanner);
        }
    }

    private Scanner openFile() {
        String fileString = "test.csv";
        return new Scanner(getClass().getResourceAsStream(fileString));
    }

    private void readFile(Scanner scanner) {
        List<Column> columnList = new ArrayList<>();
        String a = scanner.nextLine();
        a = a.replace(" ", "");
        String[] values = a.split(",");

        for (int i = 1; i < values.length; i++) {
            Column column = new Column(values[i]);
            columnList.add(column);
        }

        while (scanner.hasNext()) {
            a = scanner.nextLine();
            a = a.replace(" ", "");
            values = a.split(",");

            for (int i = 0; i < columnList.size(); i++) {
                Column column = columnList.get(i);
                column.addValue(Integer.valueOf(values[i + 1]));
            }
        }

        for (int i = 0; i < columnList.size(); i++) {
            System.out.println(columnList.get(i));
        }
    }

    private void closeFile(Scanner scanner) {
        scanner.close();
    }

    public class Column {
        private List<Integer> values;

        private final String name;

        public Column(String name) {
            this.name = name;
            this.values = new ArrayList<>();
        }

        public List<Integer> getValues() {
            return values;
        }

        public void addValue(int value) {
            this.values.add(Integer.valueOf(value));
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append(name);
            builder.append(": ");
            for (int i = 0; i < values.size(); i++) {
                int value = values.get(i);
                builder.append(value);
                if (i < (values.size() - 1)) {
                    builder.append(", ");
                }
            }

            return builder.toString();
        }

    }

}

Using LinkedHashMap to store header(as Keys). LinkedHashMap preserves the insertion-order:

public void readFile() {

    Map<String, String> map = new LinkedHashMap<String, String>();
    boolean setInitValues = true, setKeys = true;
    String[] keys = null;

    while (x.hasNext()) {
        String a = x.nextLine();
        String[] values = a.split(",");

        if (setKeys) { // set keys
            keys = Arrays.copyOfRange(values, 1, values.length);
            setKeys = false;
        } else {
            if (setInitValues) { // set initial values
                for (int i = 1; i < values.length; i++)
                    map.put(keys[i - 1], values[i].trim());
                setInitValues = false;
            } else
                // continue appending values
                for (int i = 1; i < values.length; i++)
                    map.put(keys[i - 1],
                            map.get(keys[i - 1]).concat(values[i].trim()));
        }
    }
    printMap(map); // print what you got
}

void printMap(Map<String, String> map) {
    for (Map.Entry<String, String> entry : map.entrySet())
        System.out.println("Key : " + entry.getKey() + " Value : "
                + entry.getValue());
}

Output :

Key : A Value : 1876
Key : B Value : 2187
Key : C Value : 3218
Key : D Value : 4321
Key : E Value : 5432
Key : F Value : 6543
Key : G Value : 7654
Key : H Value : 8765

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM