我正在尝试读取一个BufferedReader,该文件读入包含以逗号分隔的记录的文件。我想在两个逗号之间拆分每个字符串(或记录),删除双引号,并将每个字符串放入String数组的索引中。例如:
说我在文件中有这一行:
(“0001”,“00203”,“82409”(换行符)
“0002”,“00204”,“82500”(换行)
等等。)
我想将0001放入一个String数组[1],我想将00203放入String数组[2],依此类推......
以下代码遍历文件,将第二列中的所有记录放入String数组[2]。这意味着,在执行下面的代码后,如果我执行System.out.println(arr [2]),它将打印00203和00204,而我希望数组[2]为00203,数组[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;
Commons 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;
}
这些修改中很少有适合您的。
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;
您是否尝试过使用scanner类以及scanner.nextInt()。你不需要做条纹。
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()]);
未经测试:
arr = str.replaceAll("\"", "").replaceAll("(","").replaceAll(")","").split(",");