Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma-separated records into String Array?

I am trying to read a BufferedReader that reads in a file containing records separated by commas. I would like to split each string (or record) in between two commas, strip the double quotes, and put each of those into an index of a String array. For example:

say I have this line in the file:

("0001", "00203", "82409" (newline)

"0002", "00204", "82500" (newline)

etc.)

I want to put 0001 into a String array[1], I want 00203 into String array[2], and so on....

The following code traverses the file, putting all records in column two into String array[2]. This means, after I execute the code below, if I do System.out.println (arr[2]), it will print 00203 and 00204, whereas I would like array[2] to be 00203 and array[5] to be 00204.

Here is my code:

public String[] getArray(String source) {

FileInputStream fileinput = new FileInputStream(source);
GZIPInputStream gzip = new GZIPInputStream(fileinput);
InputStreamReader inputstream = new InputStreamReader(gzip);
BufferedReader bufr = new BufferedReader(inputstream);

String str = null;
String[] arr = null;
    while((str = bufr.readLine()) != null) {
    arr = str.replace("\"", "").split("\\s*,\\s*");
}
return arr;
like image 528
user1812747 Avatar asked Sep 12 '26 21:09

user1812747


1 Answers

Commons CSV was designed for your specific use case. Let's not reinvent the wheel, the code below will result in a GZipped CSV being parsed into fields and lines and seems to be what you're trying to do.

public String[][] getInfo() throws IOException {
    final CSVParser parser = new CSVParser(new FileReader(new InputStreamReader(new GZIPInputStream(fileinput)), CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true));
    String[][] result = parser.nextRecord().values();
    return result;
}
like image 143
hd1 Avatar answered Sep 15 '26 11:09

hd1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!