简体   繁体   中英

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;

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;
}

Have you tried using the scanner class as well as scanner.nextInt(). you do not need to do striping then.

Scanner s = new Scanner(inputstream);
ArrayList<String> list = new ArrayList<String>();

while (s.hasNextInt())
    list.add(s.nextInt());
String[] arr = list.toArray(new String[list.size()]);

Few of these modifications should work for you.

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;
List<String> numbers = new LinkedList<String>;

while((str = bufr.readLine()) != null) {
   String[] localArr = str.split(",");
   for(String intString : localArr){
    numbers.add(intString.trim());
   }
}
return arr;

未经测试:

arr = str.replaceAll("\"", "").replaceAll("(","").replaceAll(")","").split(",");

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