本文介绍了逗号分隔的记录到字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取BufferedReader,该BufferedReader读取包含以逗号分隔的记录的文件。我想在两个逗号之间分割每个字符串(或记录),去除双引号,然后将每个引号放入String数组的索引中。例如:

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:

说我在文件中有此行:

( 0001, 00203 , 82409(换行符)

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

0002, 00204, 82500(换行符)

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

etc。)

我想将0001放入字符串数组[1],
我希望将00203放入字符串数组[2],
依此类推。...

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

以下代码遍历文件,将第二列中的所有记录放入String数组[2]。这意味着,在执行以下代码后,如果执行System.out.println(arr [2]),它将打印00203和00204,而我希望array [2]为00203,array [5]为00204。

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.

这是我的代码:

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;


推荐答案

是为您的特定用例设计的。滚轮,下面的代码将导致将GZipped CSV解析为字段和行,这似乎就是您要执行的操作。

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

这篇关于逗号分隔的记录到字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 09:37