简体   繁体   中英

Java read csv file as matrix

I'm new to writing java code as such. I have experience writing code in scripting type languages. I'm trying to rewrite a piece of code I had in python in java.

Python code below -

import pandas as pd
myFile = 'dataFile'
df = pd.DataFrame(pd.read_csv(myFile,skiprows=0))
inData = df.as_matrix()

I'm looking for a method in java that is equivalent to as_matrix in python. This function converts the data frame into a matrix.

I did look up for sometime now but can't find a method as such that does the conversion like in python. Is there a 3rd party library or something on those lines I could use? Any direction would help me a lot please. Thank you heaps.

What you want to do is really simple and requires minimal code on your part, therefore I suggest you code it yourself. Here is an example implementation:

List<String[]> rowList = new ArrayList<String[]>();
try (BufferedReader br = new BufferedReader(new FileReader("pathtocsvfile.csv"))) {
    String line;
    while ((line = br.readLine()) != null) {
        String[] lineItems = line.split(",");
        rowList.add(lineItems);
    }
    br.close();
}
catch(Exception e){
    // Handle any I/O problems
}
String[][] matrix = new String[rowList.size()][];
for (int i = 0; i < rowList.size(); i++) {
    String[] row = rowList.get(i);
    matrix[i] = row;
}

What this does is really simple: It opens a buffered reader that will read the csv file line by line and paste the contents to an array of Strings after splitting them based on comma (which is your delimiter). Then it will add them to a list of arrays. I know this might not be perfect, so afterwards I take the contents of that list of arrays and turn it into a neat 2D matrix. Hope this helps.

Hint: there are a lot of improvements that could be made to this little piece of code (ie take care of trailing and leading spaces, add user-defined delimiters etc.), but this should be a good starting point.

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