简体   繁体   中英

Read data from a CSV into a nested array in Java

I'm trying to turn a .csv file in the following form (with an arbitrary number of columns):

a,b,c
d,e,f
g,h,i

into an int[][] like so:

int[][] a = {{a,b,c},{d,e,f},{g,h,i}}

in Java. How would I go about doing this?

I'm not going to give the whole answer (there are parts you should be able to look up yourself), but:

1) Use split() to split up an input line into fields. The result is a String[] .

2) The most straightforward way to convert each String to an int is by using streams. If fields is the String[] , then you can use:

 int[] ints = Arrays.stream(fields).mapToInt(Integer::parseInt).toArray();

This assumes there aren't any parse errors. If you want to handle invalid input gracefully, you may need to use a loop instead of a stream.

To break this down: Arrays.stream creates a "stream" that gives you all the Strings in the array. mapToInt turns the stream into an IntStream (a stream of int ; note that there are special stream types when the elements have a primitive type like int ). It does this by applying a method, Integer.parseInt , that takes a String parameter and returns an int . toArray on an IntStream then builds an int[] from the stream.

3) Use an ArrayList<int[]> to hold an array of all lines, since you don't know beforehand how many lines there will be. If you want an int[][] , you can convert the ArrayList to an array later.

The easiest way to do this is to use one of the many CSV-parsers which you can find on the internet. For example https://commons.apache.org/proper/commons-csv/

If you want to do it manually, you can read your file line by line and use a StringTokenizer to Split each line into tokens which you can then parse into the appropriate Java type.

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