Comma-separated records into String Array?

谁都会走 提交于 2019-12-07 17:14:17

问题


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;

回答1:


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



回答2:


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;



回答3:


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()]);



回答4:


Not tested:

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


来源:https://stackoverflow.com/questions/13312120/comma-separated-records-into-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!