我正在尝试读取一个 BufferedReader,它读取包含用逗号分隔的记录的文件。我想将每个字符串(或记录)拆分在两个逗号之间,去掉双引号,然后将每个字符串放入字符串数组的索引中。例如:
假设我的文件中有这一行:
(“0001”,“00203”,“82409”(换行符)
“0002”、“00204”、“82500”(换行符)
etc.)
我想将 0001 放入字符串数组[1]中,
我想将 00203 放入字符串数组[2]中,
等等....
以下代码遍历文件,将第二列中的所有记录放入 String array[2] 中。这意味着,在执行下面的代码后,如果我执行 System.out.println (arr[2]),它将打印 00203 和 00204,而我希望 array[2] 为 00203,array[5] 为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;
共享 CSV http://commons.apache.org/csv专为您的特定用例而设计。让我们不要重新发明轮子,下面的代码将导致 GZipped CSV 被解析为字段和行,这似乎就是您想要做的。
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)